如何优化改变3d的值数字阵列如果满足条件

2024-03-29 12:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Ubuntu上开发python-Open-CV。 我对python相当陌生,我觉得我的代码没有得到优化。在

最终目标是将像素颜色更改为jpeg图像。假设红色通道值为<;255,我将其设置为255。在

为此,我将jpeg转换为数字阵列一。 然后使用“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()

这个代码有效。但是,我觉得既不优雅也不高效。在

如何优化代码并使其更高效?在


Tags: andthe代码inposimageimportlt
2条回答

如果img是一个mxnx3 numpy数组,则以下内容将更改第三个就地组件:

np.maximum(img[..., 2], 255, out=img[..., 2])

对于RGB图像如何?在

img[img[:, :, 0] < 255, 0] = 255

使用这个方法,我们从图像的红色通道创建一个布尔掩码,并检查其值是否小于255。如果是,那么我们将这些值设置为255。在

OpenCV将图像读取为BGR,因此:

^{pr2}$

是合适的。在

或者,您也可以:

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

相关问题 更多 >