

# https://www.globalsino.com/ICs/
# Crop from image defined by a pixel line

from PIL import Image
import cv2
import numpy as np
import os

# =========== Beginning of definition everytime ==============
imagePath = r"C:\0Python\0testingCodes"
imageFile = os.path.join(imagePath, "RotatedImage.jpg")
croppedFilename = os.path.join(imagePath, "CroppedImage.jpg")                         
xDelta = 100 # Then, the image width is 200 pixels
yDelta = 50 # Then, the image higth is 100 pixels
# =========== Eend of definition everytime ==============

def cropTheImage(CoordinateList):
    img = cv2.imread(imageFile)
    h, w, _ = img.shape
    print("The height and width of the original image is: ", h, w)
    print("CoordinateList of the two selected points is ", CoordinateList)

    img = Image.open(imageFile)
    averageOfY = (CoordinateList[0][1]+CoordinateList[1][1])/2
    averageOfX = (CoordinateList[0][0]+CoordinateList[1][0])/2
    print("averageOfY is: ", averageOfY)
    print("averageOfX is: ", averageOfX)
    
    area = (averageOfX-xDelta, averageOfY-yDelta, averageOfX+xDelta, averageOfY+yDelta)
    cropped_img = img.crop(area)
    theCropped_img = cropped_img.save(croppedFilename)
    cropped_img.show()
    croppedImage = cv2.imread(croppedFilename)
    cropped_h, cropped_w, _ = croppedImage.shape
    print("Height and width of the cropped image are ", cropped_h, cropped_w)

CoordinateList = []
def click_event(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        # print(x,",",y)
        CoordinateList.append([x,y])
        font = cv2.FONT_HERSHEY_SIMPLEX
        strXY = str(x)+", "+str(y)
        cv2.putText(img, strXY, (x,y), font, 0.5, (0,0,255), 2)
        cv2.imshow("image", img)        

        if len(CoordinateList) == 2:
            cropTheImage(CoordinateList)
        
img = cv2.imread(imageFile)
cv2.imshow("image", img)
cv2.setMouseCallback("image", click_event)
cv2.waitKey(0)
cv2.destroyAllWindows()



