import cv2
import matplotlib.pyplot as plt
def detect_defect(check_binary,template):
    height,width = template.shape
    roi = cv2.resize(check_binary,(width,height))
    mask = cv2.subtract(template,roi)
    se = cv2.getStructuringElement(cv2.MORPH_RECT, (22, 22), (-1, -1))
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se)
    ret, mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
    count = 0
    for row in range(height):
        for col in range(width):
            pv = mask[row, col]
            if pv == 255:
                count += 1

    cv2.imwrite("mask.png", mask)
    return count

template = cv2.imread("./images/good_template.png", 0)
check_image = cv2.imread("./images/check_template.png",0)
detect_defect(check_image,template)
mask = cv2.imread("mask.png",0)
plt.imshow(mask,cmap="gray")
plt.show()
