lorelayb
lorelayb

Reputation: 33

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

I'm trying to make a script in which I can draw the contour of every shape in an image, which works in some cases but fails when the shape has some degradations in the color. It was meant to draw the contour of the shape (a rectangle in this case) but could not draw the whole rectangle and also added some point inside which is a false positive. Is there a way I can add less sensitivity to the script or another tool that could help me to achieve this?

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))

Upvotes: 0

Views: 1020

Answers (1)

pippo1980
pippo1980

Reputation: 3023

Change threshold values with:

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

Upvotes: 1

Related Questions