Reputation: 686
I have a image consisting N
almost 90 times but I am getting 105 contours using below code:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#cv2.imshow("Image", gray)
#cv2.waitKey(0)
blurred = cv2.GaussianBlur(gray, (5, 5), 0) #blur to reduce noise
#cv2.imshow("Image", blurred)
#cv2.waitKey(0)
# perform edge detection, find contours in the edge map, and sort the
# resulting contours from left-to-right
edged = cv2.Canny(blurred, 30, 150) #30, 150
#cv2.imwrite("test.png", edged)
#cv2.imshow("Image", edged)
#cv2.waitKey(0)
#find contours of characters(objects) in images
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
if cnts:
cnts = sort_contours(cnts, method="left-to-right")[0]
cv2.drawContours(image, cnts, -1, (0, 0, 255), 2)
cv2.imwrite("all_contours.jpg", image)
I have tried different combinations in Canny
and findContours
function but cant get the contours equal to the number of N
in image
.
Looking at the contours image, I cant see where is the problem. Any help or hint will be appreciated.
P.S : this image is an ideal image for testing. In real scenario, image will be taken from webcam.
Upvotes: 0
Views: 500
Reputation: 899
Try without Bluring image.
import cv2
image = cv2.imread("n.png")
image = cv2.resize(image, (800, 800))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.putText(image, "contours found in image : " + str(len(contours)), (20, 20), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0),1)
cv2.drawContours(image, contours, -1, (0, 0, 255), -1)
cv2.imshow("contour_image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Upvotes: 1