如何优化此代码(python中的双循环)?

时间:2019-07-31 23:37:13

标签: python loops numpy opencv

我有以下代码:

for x in range(len(img)):
    for y in range(len(img[0])):
        if img[x][y]==255 :
            imgblur[x][y]=imggray[x][y]

我对此进行了改进:

i, j = np.where(img == 255)
for x in range(i.shape[0]):
    imgblur[i[x]][j[x]]=imggray[i[x]][j[x]]

是否有一种方法可以改善更多(更快的循环)?

2 个答案:

答案 0 :(得分:0)

尝试np.where(),它表示:

if img==255 then imgblur = imgray else imgblur = imgblur

nx, ny = 5, 10
img = np.random.randint(255, size=(nx, ny))
imgblur = np.random.uniform(0,1.0,size=(nx, ny))
imggray = np.random.uniform(0,1.0,size=(nx, ny))

imgblur =   np.where(img==255,imggray,imgblur)
imgblur

答案 1 :(得分:0)

您可以尝试:

imgblur[imggray==255]=255

示例代码:

import cv2
import numpy as np

img = cv2.imread('imgs/car1.jpg')

imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

imgblur = np.zeros_like(imggray)
imgblur[imggray > 200] = 255

cv2.imshow('imggray', imggray)
cv2.imshow('imgblur', imgblur)

cv2.waitKey(0)

imggray:
imggray

imgblur:
enter image description here