如何修剪轮廓线?

时间:2019-02-09 18:08:43

标签: python opencv

我正在编写一个检测鹦鹉的眼睛的代码。目前,我正在使用在youtube上找到的已经编写的代码。它可以很好地处理我拥有的图片,但是我不知道如何显示所选区域的彩色版本。

结果:(https://imgur.com/a/zCARrVC

我尝试使用遮罩,并使用cv2.drawcontourns在其上重复已绘制的轮廓。它起作用了,但是我无法使蒙版与原始图像重叠并裁剪。我认为这是因为轮廓未填充,但是我不确定,也不知道填充轮廓是否不会与其余代码混淆。

import cv2
import numpy as np
import imutils

def nothing(x):
pass

# Load an image
img = cv2.imread('papagaio.png')

# Resize The image
if img.shape[1] > 600:
img = imutils.resize(img, width=600)

# Create a window
cv2.namedWindow('Treshed')

# create trackbars for treshold change
cv2.createTrackbar('Treshold','Treshed',0,255,nothing)


while(1):

# Clone original image to not overlap drawings
clone = img.copy()

# Convert to gray
gray = cv2.cvtColor(clone, cv2.COLOR_BGR2GRAY)

# get current positions of four trackbars
r = cv2.getTrackbarPos('Treshold','Treshed')

# Thresholding the gray image
ret,gray_threshed = cv2.threshold(gray,r,255,cv2.THRESH_BINARY)

# Blur an image
bilateral_filtered_image = cv2.bilateralFilter(gray_threshed, 5, 175, 175)

# Detect edges
edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)

# Find contours
contours, _= cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    # approximte for circles
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) > 8) & (area > 30) ):
        contour_list.append(contour)

# Draw contours on the original image
cv2.drawContours(clone, contour_list, -1, (255,0,0), 2)  


# there is an outer boundary and inner boundary for each eadge, so contours double
print('Number of found circles: {}'.format(int(len(contour_list)/2)))

#Displaying the results     
cv2.imshow('Objects Detected', clone)
cv2.imshow("Treshed", gray_threshed)


# ESC to break
k = cv2.waitKey(1) & 0xFF
if k == 27:
    break

# close all open windows
cv2.destroyAllWindows()'

1 个答案:

答案 0 :(得分:0)

就像您说的那样,您可以创建遮罩,然后将其应用于RGB图像。这是一些方法:

mask = np.zeros( (clone.shape[0], clone.shape[1]), np.uint8) #create single channel mask
for contour in contours:
    cv.fillPoly(mask, pts=[contour], color=(255)) #cv.drawContours with thickness parameter = -1 should also work
cv.bitwise_and(clone, clone, mask)