
# https://www.globalsino.com/ICs/
# Average columns and rows

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy.spatial import distance

img = cv2.imread(r"C:\GlobalSino2\ICs\images\4367c.jpg")

# Convert the image in grayscale
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
image_center = np.asarray(image.shape)/2
print("Number of shapes {0}".format(len(contours)))
image_center = tuple(image_center.astype('int32'))
# Lable image center in green
cv2.circle(img, image_center, 3, (0, 255, 0), 2)


for cnt in contours:
    M = cv2.moments(cnt)

    if M["m00"] > 3000: # M["m00"] != 0:
        # (cx, cy) is center of each contour
        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
        contour_center = (cx, cy)
        center = (cx, cy)
        # calculate distance to image_center
        distances_to_center = (distance.euclidean(image_center, contour_center))
        print(round(distances_to_center*100)/100)
        area = cv2.contourArea(cnt)

    else:
        # set values as what you need in the situation
        cx, cy = 0, 0
    center = (cx, cy)
    area = cv2.contourArea(cnt)
    perimeter = cv2.arcLength(cnt, True)

    cv2.putText(img, "A: {0:2.1f}".format(area), center,
                cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.3, (255, 0, 0), 3)

    cv2.putText(img, "P: {0:2.1f}".format(perimeter), (cx, cy+30),
                cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.3, (255, 0, 0), 3)

plt.figure("Exmaple")

plt.imshow(img)
plt.show()



