[英]colour contour on grayscale image
I made a simple code to find the contour of an object in an image.我编写了一个简单的代码来查找图像中 object 的轮廓。
img = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(img_enhanced,(25,25),0) # apply blur for contour
ret, binary = cv2.threshold(blur,1,255,cv2.THRESH_BINARY) # apply threshold to blur image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # find countour
obj_index = contours.index(max(contours, key=len)) # find index of largest object
contour_img = cv2.drawContours(img, contours, obj_index, (0,255,0), 3) # draw coutour on original image
plt.imshow(contour_img)
plt.show()
The original image is already grayscale but anyway I applied cv2.IMREAD_GRAYSCALE when I import the image.原始图像已经是灰度,但无论如何我在导入图像时应用了 cv2.IMREAD_GRAYSCALE。
And I thought if I apply the grayscale image when I 'Draw' contour, with below syntax,我想如果我在“绘制”轮廓时应用灰度图像,语法如下,
contour_img = cv2.drawContours(img, contours, obj_index, (0,255,0), 3)
I can have a grayscale image with colored contour, but it shows weird colored image.我可以有一个带有彩色轮廓的灰度图像,但它显示出奇怪的彩色图像。
How can I draw a colored contour line on the grayscale image?如何在灰度图像上绘制彩色轮廓线?
Thanks in advance提前致谢
image sample: black background and white object图片样本:黑色背景和白色 object
Based on my comment:根据我的评论:
Try something like this and tell me if it works or not尝试这样的事情并告诉我它是否有效
Edit: I have changed the threshold range.编辑:我改变了阈值范围。
cv2.threshold(blur,25,255,cv2.THRESH_BINARY)
img = cv2.imread(file_path, 1)
print(img.shape) # this should give you (img_h, img_w, 3)
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(img2,(25,25),0) # apply blur for contour
ret, binary = cv2.threshold(blur,25,255,cv2.THRESH_BINARY) # apply threshold to blur image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # find countour
obj_index = contours.index(max(contours, key=len)) # find index of largest object
contour_img = cv2.drawContours(img, contours, obj_index, (0,255,0), 3) # draw coutour on original image
plt.imshow(contour_img, cmap='gray')
plt.show()
plt.hist(blur.ravel(), bins=50)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.