target per shape_sample.py 1.74 KB
import cv2
import numpy as np

font = cv2.FONT_HERSHEY_COMPLEX

#file_path = "../../data/MICCAI_BraTS_2019_Data_Training/train_frame_m1"

# for path, dirs, files in os.walk(file_path):
#     for filename in files:

img = cv2.imread("BraTS19_2013_2_1_seg_flair_8.png", cv2.IMREAD_GRAYSCALE)
 # (img, threshold_value, value, flag): if pixel val >= threshold_value: pixel_val = value
_, threshold = cv2.threshold(img, 1, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

color = (255,255,255)
n_ellipse, n_circle = 0, 0
area = cv2.contourArea(contours[0])

for cnt in contours:
    approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
    cv2.drawContours(img, [approx], 0, (0), 5)
    x = approx.ravel()[0]
    y = approx.ravel()[1]
    
    print(area)
    if (area < cv2.contourArea(cnt)):
            area = cv2.contourArea(cnt)

    # ss = ""
    
    # if len(approx) == 3:
    #     cv2.putText(img, "Triangle", (x, y), font, 1, color)
    # elif len(approx) == 4:
    #     cv2.putText(img, "Rectangle", (x, y), font, 1, color)
    # elif len(approx) == 5:
    #     cv2.putText(img, "Pentagon", (x, y), font, 1, color)
    if len(approx) < 12:
        cv2.putText(img, "Ellipse", (x, y), font, 1, color)
        n_ellipse = n_ellipse + 1
        # if (area < cv2.contourArea(cnt)):
        #     area = cv2.contourArea(cnt)
        #     ss = "ellipse"
    else:
        cv2.putText(img, "Circle", (x, y), font, 1, color)
        n_circle = n_circle + 1
        # if (area < cv2.contourArea(cnt)):
        #     area = cv2.contourArea(cnt)
        #     ss = "circle"

print(n_ellipse, n_circle)
#print(ss)

cv2.imshow("shapes", img)
cv2.imshow("Threshold", threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()