python – 如何使用OpenCV和掩码从图像中选择好的颜色?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 如何使用OpenCV和掩码从图像中选择好的颜色?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2342字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试选择图片中的颜色.我正在使用OpenCV这样做,我正在从第https://realpython.com/python-opencv-color-spaces/页学习.我正在处理的图像刚刚显示.
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()
这是我得到的:
显然,面具没有完成它的工作……我不明白为什么.我玩了绿色的价值但我没有得到任何东西……
我的错误在哪里?
解决方法:
你的颜色范围还不是很正确. inRange()函数中的变量也是错误的顺序.它是从 – 到,所以深色必须是第一个.将您的代码更改为cv2.inRange(hsv_nucl,green2hsv,greenhsv)您可以使用/调整下面代码中的值,这是有效的.
结果:
白色背景:
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()
内容总结
以上是互联网集市为您收集整理的python – 如何使用OpenCV和掩码从图像中选择好的颜色?全部内容,希望文章能够帮你解决python – 如何使用OpenCV和掩码从图像中选择好的颜色?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。