简体   繁体   English

并行处理图像像素

[英]Process image pixels in parallel

I am looking for an efficient way to parallelize the computations in the two loops, since it take too much time to get the result我正在寻找一种有效的方法来并行化两个循环中的计算,因为获得结果需要太多时间

import numpy as np
import cv2
from utils import distort_point

img = cv2.imread('test.png')
height, width, channel = img.shape

n_width = int(width/2)
n_height = int(height/2)

dist_image = np.zeros((n_height,n_width,channel))

for i in range(height):
    for j in range(width):
        point = distort_point((j,i))

        x,y = point[0],point[1]

        if x <0:
            x = 0
        if y <0:
            y = 0
        if x>n_width-1:
            x = n_width-1
        if y>n_height-1:
            y = n_height-1
        dist_image[y,x,:] = img[i,j,:]

cv2.imwrite('out_test.jpg',dist_image)

basically, the distort_point function takes a pixel coordinates and map it to another coordinates using some math computations.基本上, distort_point 函数采用像素坐标并使用一些数学计算将其映射到另一个坐标。 set the output to the image boundaries if it's outside the limits, then move the pixel value to the new position (in another image)如果超出限制,则将输出设置为图像边界,然后将像素值移动到新位置(在另一个图像中)

You can use Numba to speed up your computation.您可以使用Numba来加快计算速度。

Numba provides JIT compilation of your code. Numba 为您的代码提供 JIT 编译。 Because your code is quite simple you just need to wrap it in a function and use the njit decorator (equivalent to @jit(nopython=True)因为您的代码非常简单,您只需要将其包装在一个函数中并使用njit装饰器(相当于@jit(nopython=True)

So for example:例如:

from numba import njit

@njit
def process(img):
    ...
    # your code here below 'img = cv2.imread('test.png')'
    return dist_image

dist_image = process(img)

cv2.imwrite('out_test.jpg',dist_image)

You also need to apply the same decorator to distort_point definition您还需要将相同的装饰器应用于distort_point定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM