Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Crom image from white background image. #python #opencv #PIL
import cv2
import numpy as np
from PIL import Image
def nparray_to_rgb(nparry:np.array):
return (int(nparry[0]),int(bg_color[1]),int(bg_color[2]))
def find_edge(img_path:str):
img = cv2.imread(img_path,0)
blur = cv2.blur(img,(5,5))
edges = cv2.Canny(blur,100,200)
return edges
def find_target(edges):
results = np.where(edges==255)
top = np.min(results[0])
bottom = np.max(results[0]) - 1
left = np.min(results[1])
right = np.max(results[1]) - 1
return (left,top,right,bottom)
def to_RGB(image:Image):
if image.mode == 'RGB': return image
background = Image.new("RGB", image.size, (255, 255, 255))
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
background.format = image.format
return background
def get_crop_img(img_path:str):
edges = find_edge(img_path)
left,top,right,bottom = find_target(edges)
rgb_img = to_RGB(Image.open(img_path))
trim_img = rgb_img.crop((left, top, right, bottom))
return trim_img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment