如何使用OpenCV选择正确的颜色阈值来处理图像?

5
我正在尝试使用OpenCV选择图像中的绿色(方法来自这个网站)。我要处理的图像是:

enter image description here

下面是我尝试编写的代码:

import cv2
import matplotlib.pyplot as plt
import numpy as np

greenhsv = (60, 255, 255)
green2hsv=(70,100,170)
g_square = np.full((10, 10, 3), greenhsv, dtype=np.uint8)/255.0
plt.imshow(hsv_to_rgb(g_square))
plt.show()
g1_square = np.full((10, 10, 3), green2hsv, dtype=np.uint8)/255.0
plt.imshow(hsv_to_rgb(g1_square))
plt.show()

nucl = cv2.imread('./Pictures/image_nucleation_essai0.png')
nucl = cv2.cvtColor(nucl, cv2.COLOR_BGR2RGB)
plt.imshow(nucl)
plt.show()

hsv_nucl = cv2.cvtColor(nucl, cv2.COLOR_RGB2HSV)

mask = cv2.inRange(hsv_nucl, greenhsv,green2hsv)
result = cv2.bitwise_and(nucl, nucl, mask=mask)
plt.imshow(mask, cmap="gray")
plt.show()
plt.imshow(result)
plt.show()

结果如下:

结果是:

enter image description here enter image description here

所以这个掩码没有起作用。


在教程中,人们总是将图像转换为HSV格式...所以我也这样做了... - J.A
1个回答

6
您的颜色范围还不太正确。另外,inRange()函数中的变量顺序是错误的。它是从-到,所以较暗的颜色必须首先出现。将您的代码更改为cv2.inRange(hsv_nucl, green2hsv,greenhsv)。您可以使用/调整以下代码中的值,这样就可以正常工作了。
结果:
enter image description here

带有白色背景:
enter image description here

import numpy as np 
import cv2

# load image
img = cv2.imread("Eding.png")
# convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 
# set lower and upper color limits
lower_val = np.array([50,100,170])
upper_val = np.array([70,255,255])
# Threshold the HSV image to get only green colors
mask = cv2.inRange(hsv, lower_val, upper_val)
# apply mask to original image - this shows the green with black blackground
only_green = cv2.bitwise_and(img,img, mask= mask)

# create a black image with the dimensions of the input image
background = np.zeros(img.shape, img.dtype)
# invert to create a white image
background = cv2.bitwise_not(background)
# invert the mask that blocks everything except green -
# so now it only blocks the green area's
mask_inv = cv2.bitwise_not(mask)
# apply the inverted mask to the white image,
# so it now has black where the original image had green
masked_bg = cv2.bitwise_and(background,background, mask= mask_inv)
# add the 2 images together. It adds all the pixel values, 
# so the result is white background and the the green from the first image
final = cv2.add(only_green, masked_bg)

#show image
cv2.imshow("img", final)
cv2.waitKey(0)
cv2.destroyAllWindows()

1
green2hsv, greenhsv 仍然不是正确的顺序,因为第一个数组元素是无序的。不过,你的示例代码是正确的。 - Cris Luengo
@J.D. 谢谢!我还在想,是否有可能将背景颜色改为白色? - J.A
1
当然,我已经更新了代码以实现这一点。同时请看一下中间图像,它有助于您理解发生的事情。 - J.D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接