Hey everyone I try to trim an image thigh, I tried many functions but no one gives the good results that I need.
output: png image trimmed
I have many images like these and I want to trim thight I can.
code attempt:
from PIL import Image, ImageChops
import numpy as np
image=Image.open('C:\\11031\\SimpleTest\\1.png')
image.load()
image = image.crop((219, 0, 860, 1365))
image_data = np.asarray(image)
image_data_bw = image_data.max(axis=2)
non_empty_columns = np.where(image_data_bw.max(axis=0)>0)[0]
non_empty_rows = np.where(image_data_bw.max(axis=1)>0)[0]
cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))
image_data_new = image_data[cropBox[0]:cropBox[1]+1, cropBox[2]:cropBox[3]+1 , :]
new_image = Image.fromarray(image_data_new)
new_image.save('L_2d_cropped.png')
Thank you for any help!
The background is white, and the code is implemented as if the background is black.
As simple solution is inverting the polarity at the beginning:
image_data = np.asarray(image)
image_data_inv = 255 - image_data # Invert polarity (the background is going to be black instead of white).
image_data_bw = image_data_inv.max(axis=2)
After polarity inversion, the background is going to be black, and the "object" is going to be brighter than the background.
Code sample:
from PIL import Image, ImageChops
import numpy as np
image = Image.open('1.png')
image.load()
image = image.crop((0, 219, 1365, 860)) #image = image.crop((219, 0, 860, 1365))
image_data = np.asarray(image)
image_data_inv = 255 - image_data # Invert polarity (the background is going to be black instead of white).
image_data_bw = image_data_inv.max(axis=2)
non_empty_columns = np.where(image_data_bw.max(axis=0)>0)[0]
non_empty_rows = np.where(image_data_bw.max(axis=1)>0)[0]
cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))
image_data_new = image_data[cropBox[0]:cropBox[1]+1, cropBox[2]:cropBox[3]+1 , :]
new_image = Image.fromarray(image_data_new)
new_image.save('L_2d_cropped.png')
You are saying that you have many images like these...
The above solution is going to work only for images with white background.