简体   繁体   中英

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. 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 provides JIT compilation of your code. 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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