是否可以在 python 中为 drawcontour 中的特定区域着色?

is it possible to color specific area in drawcontour in python?

我在 python 从事图像处理工作,我使用 cv2.minAreaRect 检测补丁并绘制旋转矩形,我实现了这个。

现在我要将检测到的patch全部用白色填充,也就是cv2.drawContour里面的青色里面的区域全部用白色填充(ms-paint中已经做了desire输出,供参考) 我想在python中实现,在OpenCV中是否可行-python?

假设您在 cnts 中保存了等高线。然后下面的代码片段将用青色填充旋转的矩形。

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

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

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