问题描述
我想对图像设置阈值,但我希望输出不是黑白的,而是白色和其他颜色的。我能够使用嵌套的 for 循环来实现这一点,但是这很慢,我想知道是否有人知道使用 CV2 功能有效地做到这一点的任何方法。
img = cv2.imread("Naas.png",1)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
threshold,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY)
# Changing black to green and converting from Grayscale to RGB
lis = []
for i in thresh:
for j in i:
if j == 0:
lis.append((0,0))
else:
lis.append((255,255))
img = np.array(lis,dtype = "uint8")
img = img.reshape(thresh.shape[0],thresh_inv.shape[],3)
此循环将阈值图像中的任何黑色像素更改为绿色。
解决方法
所以绿色通道总是 255 而红色和蓝色通道只是阈值?
所以你正在看这样的东西
import numpy as np
img = cv2.imread("Naas.png",1)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
threshold,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY)
img_result=np.ones(img.shape)*255 #set all to 255
img_result[:,:,0]=thresh[:,:] #set red channel to threshold
img_result[:,2]=thresh[:,:] #set blue channel to threshold