如何 draw/contour 图像中的形状边缘而不会出现误报?

How can I draw/contour the edges of shapes in an image without false positives?

我正在尝试制作一个脚本,我可以在其中绘制图像中每个形状的轮廓,这在某些情况下有效,但当形状颜色退化时会失败。它旨在绘制形状的轮廓(在本例中为矩形),但无法绘制整个矩形,并且还在内部添加了一些误报点。有没有一种方法可以降低脚本的敏感性或其他可以帮助我实现此目的的工具?

from __future__ import print_function
import os
import imutils
import cv2
from PIL import Image
import numpy as np


print("OpenCV Version: {}".format(cv2.__version__))
image = cv2.imread("input.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1]
if imutils.is_cv2() or imutils.is_cv4():
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_NONE)
elif imutils.is_cv3():
    (_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_NONE)

cv2.drawContours(image, cnts, -1, (50, 50, 50),24)

RGBimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
PILimage = Image.fromarray(RGBimage)
PILimage.save('output.png', dpi=(300,300))

更改阈值:

thresh = cv2.threshold(灰色, 250, 255, cv2.THRESH_BINARY_INV)[1]