【问题标题】:colour contour on grayscale image灰度图像上的颜色轮廓
【发布时间】:2020-09-22 11:05:37
【问题描述】:

我编写了一个简单的代码来查找图像中对象的轮廓。

    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()

原始图像已经是灰度的,但是我在导入图像时应用了 cv2.IMREAD_GRAYSCALE。

我想如果我在“绘制”轮廓时应用灰度图像,语法如下,

contour_img = cv2.drawContours(img, contours, obj_index, (0,255,0), 3)

我可以有一个带有彩色轮廓的灰度图像,但它显示 奇怪的彩色图像。

如何在灰度图像上绘制彩色轮廓线?

提前致谢

图像样本:黑色背景和白色物体

【问题讨论】:

  • 你能张贴图片(奇怪的彩色图片)吗?你是黄色,紫色吗?
  • @Pygirl 哦。是的。完全正确。
  • 实际上,当您使用 matplotlib 绘制灰度图时,它会显示(紫色-> 黑色、黄色--> 白色)使用:plt.show(contour_img, cmap='gray)
  • 顺便说一句,您不能将彩色线绘制到灰度图像上。因为看到,对于彩色图像会有 rgb 分量。但你的灰度图像没有。所以我会建议你使用 2 张图片。按原样打开图像(检查它的形状,它将为您提供通道 3 或 4)这将是您的 img1,img2 将是 img1 的灰度(转换后)。使用 img2 获取轮廓,使用 img1 绘制轮廓。
  • @Pygirl 是的,这就是我想要的。但是怎么做?

标签: python contour cv2


【解决方案1】:

根据我的评论:

试试这样的方法,告诉我它是否有效

编辑:我更改了阈值范围。 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)


【讨论】:

  • 彩色线'是'在灰色图像上,但轮廓线始终是整个图像的轮廓,而不是对象。但在它检测到物体之前。
  • 或多或少看起来像上图。黑色背景和白色物体
  • 实际上您的代码一开始就无法捕获轮廓。它没有正确二值化。
  • 检查我编辑的答案。范围不太好。您可以绘制直方图以查看像素频率以确定阈值。 plt.hist(blur.ravel())
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 2013-05-08
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
相关资源
最近更新 更多