如果满足条件,如何优化更改3d numpy.array的值
问题内容:
我正在使用python-在Ubuntu上打开CV。我是python的新手,我感觉我的编码没有优化。
最终目标是将像素颜色更改为jpeg图像。假设红色通道值<255,则将其设置为255。
为此,我将jpeg转换为numpy.array。然后使用“ for / in:”循环,逐像素检查红色通道是否小于255。如果满足条件,则将值更改为255。
我的代码:
import numpy
import cv2
img=cv2.imread('image.jpeg',1)
y=x=-1 # I use y and x as a counters.
#They will track the pixel position as (y,x)
for pos_y in img:
y=y+1; x=-1 #For each new column of the image x is reset to -1
for pos_x in pos_y:
x=x+1
b, g, r = pos_x # I get the blue, green and red color
# please note that opencv is bgr instead of rgb
if r < 255:
r = 255
pos_x = [b,g,r]
img[y,x] = pos_x
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
此代码有效。但是,我感觉既不优雅也不高效。
如何优化代码并使其更高效?
问题答案:
RGB图像呢?
img[img[:, :, 0] < 255, 0] = 255
使用此方法,我们从图像的红色通道创建一个布尔蒙版,并检查其值是否小于255。如果是,则将这些值设置为255。
OpenCV将图像读取为BGR
,因此:
img[img[:, :, 2] < 255, 2] = 255
将是适当的。
或者,您也可以执行以下操作:
mask_R = img < 255)[:, :, 2]
img[mask_R, 2] = 255
例:
In [24]: a
Out[24]:
array([[[168],
[170],
[175]],
[[169],
[170],
[172]],
[[165],
[170],
[174]]])
In [25]: a > 170
Out[25]:
array([[[False],
[False],
[ True]],
[[False],
[False],
[ True]],
[[False],
[False],
[ True]]], dtype=bool)
使用以上条件(a > 170
),我们生成一个布尔掩码。现在,假设您采用任何一个通道并将其放置在此布尔掩码的顶部。当我们分配新值时,无论蒙版有何true
值,图像数组中的相应元素都将被重置为新值。
# we just filter out the values in array which match our condition
In [36]: a[a > 170]
Out[36]: array([175, 172, 174])
# assign new values. Let's say 180
In [37]: a[a > 170] = 180
In [38]: a
Out[38]:
array([[[168],
[170],
[180]], # <== new value
[[169],
[170],
[180]], # <== new value
[[165],
[170],
[180]]]) # <== new value