问题描述
我有一张带有橙色盖子位置的咖啡罐的图像,我想找到它.这是 .
i have an image of a coffee can with an orange lid position of which i want to find. here is it .
gcolor2 实用程序显示盖子中心的 hsv 为 (22, 59, 100).问题是如何选择颜色的界限呢?我尝试了 min = (18, 40, 90) 和 max = (27, 255, 255),但得到了意外
gcolor2 utility shows hsv at the center of the lid to be (22, 59, 100). the question is how to choose the limits of the color then? i tried min = (18, 40, 90) and max = (27, 255, 255), but have got unexpected
这是 python 代码:
here is the python code:
import cv in_image = 'kaffee.png' out_image = 'kaffee_out.png' out_image_thr = 'kaffee_thr.png' orange_min = cv.scalar(18, 40, 90) orange_max = cv.scalar(27, 255, 255) color_min = orange_min color_max = orange_max def test1(): frame = cv.loadimage(in_image) framehsv = cv.createimage(cv.getsize(frame), 8, 3) cv.cvtcolor(frame, framehsv, cv.cv_rgb2hsv) frame_threshed = cv.createimage(cv.getsize(framehsv), 8, 1) cv.inranges(framehsv, color_min, color_max, frame_threshed) cv.saveimage(out_image_thr, frame_threshed) if __name__ == '__main__': test1()
推荐答案
问题一: 不同的应用程序对 hsv 使用不同的尺度.例如 gimp 使用 h = 0-360, s = 0-100 和 v = 0-100.但是 opencv 使用 h: 0-179, s: 0-255, v: 0-255.在这里,我在 gimp 中得到了 22 的色调值.所以我拿了一半,11,并为此定义了范围.即(5,50,50) - (15,255,255).
problem 1 : different applications use different scales for hsv. for example gimp uses h = 0-360, s = 0-100 and v = 0-100. but opencv uses h: 0-179, s: 0-255, v: 0-255. here i got a hue value of 22 in gimp. so i took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255).
问题 2: 而且,opencv 使用 bgr 格式,而不是 rgb.因此,如下更改将 rgb 转换为 hsv 的代码:
problem 2: and also, opencv uses bgr format, not rgb. so change your code which converts rgb to hsv as follows:
cv.cvtcolor(frame, framehsv, cv.cv_bgr2hsv)
现在运行它.我得到如下输出:
now run it. i got an output as follows:
希望这是您想要的.有一些错误检测,但它们很小,因此您可以选择最大的轮廓即您的盖子.
hope that is what you wanted. there are some false detections, but they are small, so you can choose biggest contour which is your lid.
正如 karl philip 在他的评论中所说,添加新代码会很好.但是只有一行的变化.因此,我想在新的 cv2 模块中添加相同的代码,以便用户可以比较新的 cv2 模块的易用性和灵活性.
as karl philip told in his comment, it would be good to add new code. but there is change of only a single line. so, i would like to add the same code implemented in new cv2 module, so users can compare the easiness and flexibility of new cv2 module.
import cv2 import numpy as np img = cv2.imread('sof.jpg') orange_min = np.array([5, 50, 50],np.uint8) orange_max = np.array([15, 255, 255],np.uint8) hsv_img = cv2.cvtcolor(img,cv2.color_bgr2hsv) frame_threshed = cv2.inrange(hsv_img, orange_min, orange_max) cv2.imwrite('output2.jpg', frame_threshed)
它给出与上面相同的结果.但是代码要简单得多.
it gives the same result as above. but code is much more simpler.