并行处理图像像素

3

我正在寻找一种有效的方式来并行计算这两个循环中的内容,因为获取结果需要太长时间。

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)

基本上,distort_point函数接受一个像素坐标并使用一些数学计算将其映射到另一个坐标。如果超出了图像边界,则将输出设置为图像边界,并将像素值移动到新位置(在另一幅图像中)。

1个回答

3

您可以使用Numba来加速计算。

Numba提供了代码的即时编译。因为您的代码非常简单,只需要将其封装在一个函数中,并使用njit修饰符(相当于@jit(nopython=True))。

例如:

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)

你还需要将相同的装饰器应用到distort_point定义中。


谢谢,这正是我在寻找的。 - Silver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接