【发布时间】: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 是的,这就是我想要的。但是怎么做?