这是我正在使用的完整代码,我已经包含了输出图像。我正在尝试删除背景,然后对其应用轮廓,以便只剩下平面的轮廓。我已经附上了应用阈值和轮廓后代码中的图像
阈值之后
轮廓后
import cv2
import numpy as np
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
help="path to input image")
ap.add_argument("-o", "--output", required=True,
help="path to output image")
args = vars(ap.parse_args())
src = cv2.imread(args["input"], 1) # read input image
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) # convert to grayscale
blur = cv2.blur(gray, (3, 3)) # blur the image
# Otsu's thresholding
th2 = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,11,2)
thresh = cv2.resize(th2, (1080 , 480))
cv2.imshow("thresh",thresh)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# create hull array for convex hull points
hull = []
# calculate points for each contour
for i in range(len(contours)):
# creating convex hull object for each contour
hull.append(cv2.convexHull(contours[i], False))
# create an empty black image
drawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)
# draw contours and hull points
for i in range(len(contours)):
color_contours = (0, 255, 0) # green - color for contours
color = (255, 0, 0) # blue - color for convex hull
# draw ith contour
cv2.drawContours(drawing, contours, i, color_contours, 1, 8, hierarchy)
# draw ith convex hull object
drawing = cv2.resize(drawing, (1080 , 480))
cv2.imshow(args["output"], drawing)
cv2.destroyAllWindows()
下面是一个对区域进行过滤以获得最大轮廓的示例:
# get outer contours and filter to get the largest (presumably only one)
cntrs = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
# create black background image
result = np.zeros_like(src)
area_thresh = 0
for c in cntrs:
area = cv2.contourArea(c)
if area > area_thresh:
area_thresh = area
big_contour = c
# draw largest contour on black background
cv2.drawContours(result, [big_contour], -1, (0,0,255), 1)
如果你想保留多个轮廓,你可以在Python OpenCV中保留任何大于某个阈值的轮廓。这是之前修改的代码,用于最小面积为10000的区域。将绘制所有大于10000的等高线。
# get outer contours and filter to get the largest (presumably only one)
cntrs = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
# create black background image
result = np.zeros_like(src)
area_thresh = 10000
for c in cntrs:
area = cv2.contourArea(c)
if area > area_thresh:
cv2.drawContours(result, [c], -1, (0,0,255), 1)