Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OK. this code does not successfully draw the centroids. Where did I go wrong?

import cv2
import numpy as np

img = cv2.imread('die.jpg',0)
ret, thresh = cv2.threshold(img,225, 255,cv2.THRESH_BINARY)
cv2.imshow('Binary',thresh)

_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
img2 = img.copy()
index = -1
thickness = 4
color = (255,0,255)

cv2.drawContours(img2, contours, index, color, thickness)
cv2.imshow('contours',img2)
print(img.size)

objects = np.zeros([img.shape[0], img.shape[1],3],'uint8')
row,col,channels=objects.shape

for c in contours:

    cv2.drawContours(objects, [c],-1,color,-1)

    area = cv2.contourArea(c)
    perimeter = cv2.arcLength(c, True)

    M = cv2.moments(c)

    if area>=12000 and area<=100000: #>=660, <=100000

        value = map(lambda x: x/2, objects.shape)
        X = objects.shape[0]//2
        Y = objects.shape[1]//2

        cx = 0
        cy = 0

        if list(img.shape) >= [2445//2,2383]:

            if M['m00'] !=0:
                cx = int(M['m10']/M['m00'])
                cy = int(M['m01']/M['m00'])

        cv2.circle(objects,(cx,cy),4,(0,127,    
        print('Area: {}, preimeter: {}'.format(area,perimeter))
        print('(',cx,',',cy,')')


print(img.size)
print(img.shape)
cv2.imshow('NContours',objects)
cv2.waitKey(0)
cv2.destroyAllWindows()