gpt4 book ai didi

python - python cv中的值错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:43 25 4
gpt4 key购买 nike

我正在尝试将单色 3 channel QR 中的黑色图案更改为任何其他颜色,但我一直收到此错误

if k.any()==[0,0,0]: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我正在尝试的代码如下:

import cv2
import numpy as np
img = cv2.imread('C:/New folder (2)/new1.png')

rows,cols,bands = img.shape
print rows,cols,bands
for i in xrange (rows):
for j in xrange (cols):
k = img[i,j]
if k.any()==[0,0,0]:
img[i,j]==[255,255,255]
cv2.imshow('r',r)
cv2.waitKey(0)

我正在使用的图像附在下面。请帮助我摆脱困境。

QR Image

最佳答案

虽然我已更正您帖子中的缩进错误,但您有两个小错误:

1.) np.any() 语法错误

2.) 分配新的像素值时,您进行了比较,这对值没有影响。

附上修改后的代码和注释:

import cv2
import numpy as np
img = cv2.imread('image.png')

rows,cols,bands = img.shape
print rows,cols,bands
for i in xrange (rows):
for j in xrange (cols):
k = img[i,j]
#corrected syntax for comparison of multiple components
if np.all(k==[0,0,0]):
# Use = instead of == in next line, you do not want to compate
img[i,j]=[120,0,255]
cv2.imshow('r',img)
cv2.waitKey(0)

但是最后要说的是:我只是直接回答了你的问题,循环单个像素根本不是你应该选择的 OpenCV 解决方案。

虽然这看起来更复杂,但在 OpenCV 中更合适(也更快)的方法是这样的:

import cv2
import numpy as np
img = cv2.imread('image.png')

rows,cols,bands = img.shape
print rows,cols,bands

# Create image with new colour for replacement
new_colour_image= np.zeros((rows,cols,3), np.uint8)
new_colour_image[:,:]= (255,0,0)

# Define range of color to be exchanged (in this case only one single color, but could be range of colours)
lower_limit = np.array([0,0,0])
upper_limit = np.array([0,0,0])

# Generate mask for the pixels to be exchanged
new_colour_mask = cv2.inRange(img, lower_limit, upper_limit)

# Generate mask for the pixels to be kept
old_image_mask=cv2.bitwise_not(new_colour_mask)


# Part of the image which is kept
img2= cv2.bitwise_and(img,img, old_image_mask)

# Part of the image which is replaced
new_colour_image=cv2.bitwise_and(new_colour_image,new_colour_image, new_colour_mask)

#Combination of the two parts
result=cv2.bitwise_or(img2, new_colour_image)

cv2.imshow('image',img)
cv2.imshow('mask',new_colour_mask)
cv2.imshow('r',result)
cv2.waitKey(0)

关于python - python cv中的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36421916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com