【问题标题】:Process image pixels in parallel并行处理图像像素
【发布时间】:2020-11-24 23:51:17
【问题描述】:

我正在寻找一种有效的方法来并行化两个循环中的计算,因为获得结果需要太多时间

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 函数采用一个像素坐标并使用一些数学计算将其映射到另一个坐标。如果超出限制,则将输出设置为图像边界,然后将像素值移动到新位置(在另一个图像中)

【问题讨论】:

    标签: python opencv parallel-processing


    【解决方案1】:

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

    Numba 提供代码的 JIT 编译。因为您的代码非常简单,您只需将其包装在一个函数中并使用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 定义

    【讨论】:

    • 谢谢,这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 2023-03-22
    • 1970-01-01
    • 2012-07-21
    • 2023-03-30
    • 2011-08-17
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多