import cv2
import numpy as np

print (cv2.__version__)

RED_LOW_THRESHOLD = 220 #209
MIN_PIP_AREA = 10 #10 #60
MAX_PIP_AREA=200

def resizeRect(rect, sizeFactor):
	return (rect[0], (rect[1][0] + sizeFactor,rect[1][1] + sizeFactor), rect[2])
	
### Read anc crop the picture
img = cv2.imread("dice-white.jpg")
#img=img[0:720,100:870]

### Split into BGR (RGB)

blue = cv2.split(img)[0]
green = cv2.split(img)[1]
red = cv2.split(img)[2]
#cv2.imshow("green",green)

### Fetch the dice contours using green threshold and invert.
diceblocks = cv2.threshold(green, RED_LOW_THRESHOLD, 255, 1) # 185 --> 235
invdiceblocks = 255 - diceblocks[1]
#cv2.imshow("diceblocks",invdiceblocks)

### Find the contours
(_,pyramids,hierarchy) = cv2.findContours(invdiceblocks.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
print (str(len(pyramids)) + " dice.")

dice = cv2.cvtColor(invdiceblocks, cv2.COLOR_GRAY2RGB) #INUTILE = uniquement pour AFFICHAGE

### Look at each dice face and determine number of pips
dice_results = [0,0,0,0,0,0]
wrongdice = 0

for pyramid in pyramids:	
	pips = 0

	# get the coordinates to cut out the dice face from the image
	# with only the pips
	rect = cv2.minAreaRect(pyramid)
	floatBox = cv2.boxPoints(rect)
	intBox = np.int0(floatBox)
	a,b,c,d = cv2.boundingRect(intBox)
	
	# cut out the dice face
	subimage = invdiceblocks[b:b+d,a:a+c]
	# count the number of contours
	_,pip_contours, subhierarchy = cv2.findContours(subimage.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
	for pip in pip_contours:
		# count pips only if they are of a certain size
		if cv2.contourArea(pip) >= MIN_PIP_AREA and cv2.contourArea(pip)<=MAX_PIP_AREA :
			pips = pips + 1
		
	# log erroneous dice
	if pips > 6 or pips == 0:
		wrongdice = wrongdice + 1
		print (pips)
	else:
		dice_results[pips - 1] = dice_results[pips - 1] + 1
		cv2.putText(dice,str(pips),(a,b-5),0,1,(0,0,255)) #INUTILE = AFFICHAGE
	
# print out the results #INUTILE = AFFICHAGE
print (dice_results)
print (str(wrongdice) + " erroneous objects found.")

cv2.drawContours(dice,pyramids,-1,(255,255,0),1)
cv2.imshow('Dice', dice)
cv2.imshow('Original',img)

cv2.waitKey(0)
cv2.destroyAllWindows()
