# automated cell counting
import cv2
import numpy as np
pic = cv2.imread("cellmain.png")
print("mainpic", pic.shape)
# pic0 = cv2.imread("cell.png", 0)
cv2.imshow("cell", pic)
# cv2.imshow("cell0",pic0)
pic_gray = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(pic_gray, (5, 5), 3)
print("blur",blur.shape)
edge = cv2.Canny(blur, 20, 30, L2gradient=True)
print("edge",edge.shape)
#cv2.namedWindow("cell", cv2.WINDOW_NORMAL)
#cv2.namedWindow("blur", cv2.WINDOW_NORMAL)
#cv2.namedWindow("edge", cv2.WINDOW_NORMAL)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(blur,kernel)
edge_erosion = cv2.Canny(erosion, 20, 30, L2gradient=True)
opening = cv2.morphologyEx(pic_gray,cv2.MORPH_OPEN,kernel)
edge_opening = cv2.Canny(opening, 20, 30, L2gradient=True)
closing = cv2.morphologyEx(blur,cv2.MORPH_CLOSE,kernel)
edge_closing = cv2.Canny(closing, 20, 30, L2gradient=True)
#cv2.imshow("erosion",erosion)
#cv2.imshow("opening",opening)
#cv2.imshow("closing",closing)
#cv2.imshow("edge_erosion",edge_erosion)
#cv2.imshow("edge_opening",edge_opening)
#cv2.imshow("edge_closing",edge_closing)
gradient = cv2.morphologyEx(blur,cv2.MORPH_GRADIENT,kernel)
#tophat = cv2.morphologyEx(pic_gray,cv2.MORPH_TOPHAT,kernel)
blackhat = cv2.morphologyEx(blur,cv2.MORPH_BLACKHAT,kernel)
blackhat2 = cv2.morphologyEx(pic_gray,cv2.MORPH_BLACKHAT,kernel)
#cv2.imshow("gradient",gradient)
#cv2.imshow("tophat",tophat)
#cv2.imshow("blackhat2",blackhat2)
#Find circles
# Read image as gray-scale
#img = cv2.imread('circles.png', cv2.IMREAD_COLOR)
# Convert to gray-scale
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur the image to reduce noise
#img_blur = cv2.medianBlur(gray, 5)
# Apply hough transform on the image
circles = cv2.HoughCircles(opening, cv2.HOUGH_GRADIENT, 1, pic.shape[0]/64, param1=200, param2=10, minRadius=1, maxRadius=25)
# Draw detected circles
if circles is not None:
circles = np.uint16(np.around(circles))
count = 0
for i in circles[0, :]:
count += 1
# Draw outer circle
cv2.circle(pic, (i[0], i[1]), i[2], (0, 255, 0), 2)
# Draw inner circle
cv2.circle(pic, (i[0], i[1]), 2, (0, 0, 255), 3)
print("count", count)
cv2.namedWindow("count circle", cv2.WINDOW_NORMAL)
cv2.imshow("count circle",pic)
#Laplacian vs sobel
#laplacian = cv2.Laplacian(pic,cv2.CV_64F)
#cv2.imshow("laplacian",laplacian)
#sobelx = cv2.Sobel(pic,cv2.CV_64F,1,0,ksize=5)
#sobely = cv2.Sobel(pic,cv2.CV_64F,0,1,ksize=5)
#cv2.imshow("sobelx",sobelx)
#cv2.imshow("sobely",sobely)
#cv2.imshow("cell", pic_gray)
#cv2.imshow("blur", blur)
#cv2.imshow("edge", edge)
cv2.waitKey()