Quantcast
Channel: OpenCV Q&A Forum - RSS feed
Viewing all articles
Browse latest Browse all 2088

Object counting works not correct, why? python with opencv

$
0
0
Hello, I've got huge problem, I need to calculate the centers of the objects(coin), but when objects are close to each other, and they touching each other, center is calculated as coomon to more than one coin.So i'm using wathershed, but after that, I can't get separated centers of coins.I don't know why.Help? import numpy as np import cv2 from matplotlib import pyplot as plt import argparse import imutils import cv2 from math import sqrt, pi from matplotlib import pyplot as plt import numpy as np point = 70 img = cv2.imread('14.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray,point,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) kernel = np.ones((4,3),np.uint8) #4/3 opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2) opening = cv2.bitwise_not(opening) sure_bg = cv2.dilate(opening,kernel,iterations=3)#3 dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5) ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0) sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(sure_bg,sure_fg) ret, markers = cv2.connectedComponents(sure_fg) markers = markers+1 markers[unknown==255] = 0 markers = cv2.watershed(img,markers) img[markers == -1] = [0,0,0] gray2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #blurred = cv2.GaussianBlur(gray, (5, 5), 0) thresh2 = cv2.threshold(gray2, point, 255, cv2.THRESH_BINARY)[1] cnts = cv2.findContours(thresh2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] cv2.imshow("thresh 2", thresh2) count = 0 for c in cnts: M = cv2.moments(c) if M["m00"] != 0: cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) else: cX, cY = 0, 0 cv2.circle(img, (cX, cY), 1, (0, 0, 255), -1) cv2.putText(img, "center", (cX - 20, cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1) area = cv2.contourArea(c) #objPercent = (area/imgSize) *100 # print('AREA:'+str(objPercent)) if cX !=0 and cY != 0: count += 1 cv2.imshow("img after count", img) gray2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("gray 2", gray2) ret,thx = cv2.threshold(gray2,50,255,cv2.THRESH_BINARY) cv2.imshow('binarzyation after', thx) print('liczba obietkow:'+str(count)) ![image description](https://zapodaj.net/87529699229b0.png.html) https://zapodaj.net/87529699229b0.png.html <-- img if links higher doesn't work

Viewing all articles
Browse latest Browse all 2088

Trending Articles