【问题标题】:is it possible to color specific area in drawcontour in python?是否可以在python的drawcontour中为特定区域着色?
【发布时间】:2020-06-20 12:13:12
【问题描述】:

我在 python 中进行图像处理,我使用cv2.minAreaRect 检测补丁并绘制一个旋转的矩形,我实现了这一点。

现在我想将检测到的补丁完全填充为白色,这意味着cv2.drawContour 内部的区域为青色内部完全为白色(希望输出已在 ms-paint 中完成以供参考) 我想在python中实现,在OpenCV-python中可以吗?

【问题讨论】:

  • 只设置一个负厚度,例如thickness=-1 in drawContours

标签: python opencv image-processing ocr opencv-python


【解决方案1】:

假设您将轮廓保存在cnts 中。然后下面的 sn-p 将用青色填充旋转的矩形。

import numpy as np
import cv2

for c in cnts:
    rotrect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rotrect)
    box = np.int0(box)
    cv2.drawContours(image, [box], 0, (255, 255, 0), -1) # as opencv stores in BGR format

【讨论】:

  • 它使整个图像为青色
  • 这可能是由可能覆盖整个图像的外部轮廓引起的。您需要使用cnts = sorted(cnts, key = cv2.contourArea, reverse = True) 按区域对轮廓进行排序。然后看看是否有覆盖整个图像的轮廓。通常需要从上述循环中排除前 1 或 2 个最大轮廓。由于您没有共享原始图像和代码,因此我建议使用一个 sn-p。但是您需要根据需要过滤轮廓。
  • 很高兴知道它解决了您的问题。如果满足您的需要,您可以考虑接受答案。
【解决方案2】:

@amras 根据上述指南,我修改并发布了用于您所有参考的代码

import cv2
import numpy as np
import matplotlib.pyplot as plt


image=cv2.imread("CP150036_001bw.png",0)
im2=cv2.imread("CP150036_001.png")
# convert to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# create a binary thresholded image
_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)
# show it
plt.imshow(binary, cmap="gray")
plt.show()
# find the contours from the thresholded image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#print("contours:",contours)
# draw all contours
for c in contours:
    if cv2.contourArea(c)>70000:
        continue


    (x, y, w, h) = cv2.boundingRect(c)
    #cv2.rectangle(image, (x,y), (x+w,y+h), (0, 255, 0), 2)

    ## BEGIN - draw rotated rectangle
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    im=cv2.drawContours(image,[box],0,(255,255,255),-1)
    #im3=cv2.drawContours(im2,[box], 0, (255, 0, 0), 2)

# show the image with the drawn contours
plt.imshow(image)
#plt.imshow(im3)
#cv2.imwrite("textDectBox.png",im3)
cv2.imwrite("detectImg.png",im)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2016-11-20
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多