二值化之后进行查找轮廓
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
screenCnt = approx
break
print("STEP 2: Find contours of paper")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
二值化效果
查找轮廓效果
你想要什么效果
根据轮廓的长度和面积进行过滤。你这个最简单的操作就是保留最大轮廓,
用下面这个代码:
import cv2
import numpy as np
img = cv2.imread('test/red_che_0.jpg')
mask = img.copy()
# 二值化,100为阈值,小于100的变为255,大于100的变为0
# 也可以根据自己的要求,改变参数:
# cv2.THRESH_BINARY
# cv2.THRESH_BINARY_INV
# cv2.THRESH_TRUNC
# cv2.THRESH_TOZERO_INV
# cv2.THRESH_TOZERO
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
etVal, threshold = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY)
# 寻找轮廓
contours, hierarchy = cv2.findContours(threshold , cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
valid = len(contours) > 0
# 找到所有的轮廓
#contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
area = []
# 找到最大的轮廓
for k in range(len(contours)):
area.append(cv2.contourArea(contours[k]))
max_idx = np.argmax(np.array(area))
# 填充最大的轮廓
mask = cv2.drawContours(mask, contours, max_idx, 0, cv2.FILLED)
# 保存填充后的图像
cv2.namedWindow("mask",0)
cv2.imshow("mask", mask)
cv2.waitKey(200)