有没有一种方法可以使背景清晰,并在应用自适应阈值后仅保留最大轮廓

问题描述 投票:1回答:1

这是我正在使用的完整代码,并且包含了输出图像。我正在尝试删除背景,然后对其应用轮廓,以使剩下的唯一项是平面的轮廓。应用阈值和轮廓后,我已经从代码中附加了图像

After Threshold

After Contouring

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() 
python numpy opencv
1个回答
0
投票

这里是对区域进行滤波以获取最大轮廓的示例:

# 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)
© www.soinside.com 2019 - 2024. All rights reserved.