
# https://www.globalsino.com/ICs/
# Crop the largest portion with non-zero pixel values from an image


from PIL import Image
import cv2
import numpy as np

theImageFile = r"C:\GlobalSino2\ICs\images\4339c.jpg"

img = cv2.imread(theImageFile, cv2.IMREAD_GRAYSCALE)
imgColor = cv2.imread(theImageFile)
loc = np.nonzero(img)

top = loc[0].min()
bottom = loc[0].max()
left = loc[1].min()
right = loc[1].max()

# (0,0,255): color of the rectangle
#output = cv2.rectangle(cv2.cvtColor(img, cv2.COLOR_GRAY2BGR), (left, top), (right, bottom), (0,0,255), 1)
output = cv2.rectangle(imgColor, (left, top), (right, bottom), (0,0,255), 1)
cv2.imwrite(r"C:\GlobalSino2\ICs\images\4339c_nonzero.jpg", output)

openForCrop = Image.open(theImageFile)
area = (left,top, right, bottom)
cropedImage = openForCrop.crop(area)
cropedImage.save(r"C:\GlobalSino2\ICs\images\4339c_nonzero_colored.jpg")

   

