import numpy as np
from PIL import Image
import pprint
def get_y_top(pix, width, height, background, difference):
back_np = np.array(background)
for y in range(0, height):
for x in range(0, width):
if max(np.abs(np.array(pix[x, y]) - back_np)) > difference:
return y
def get_y_bot(pix, width, height, background, difference):
back_np = np.array(background)
for y in range(height-1, -1, -1):
for x in range(0, width):
if max(np.abs(np.array(pix[x, y]) - back_np)) > difference:
return y
def get_x_left(pix, width, height, background, difference):
back_np = np.array(background)
for x in range(0, width):
for y in range(0, height):
if max(np.abs(np.array(pix[x, y]) - back_np)) > difference:
return x
def get_x_right(pix, width, height, background, difference):
back_np = np.array(background)
for x in range(width-1, -1, -1):
for y in range(0, height):
if max(np.abs(np.array(pix[x, y]) - back_np)) > difference:
return x
img = Image.open('test.jpg')
width, height = img.size
pix = img.load()
background = pix[0,0]
difference = 20 #or whatever works for you here, use trial and error to establish this number
y_top = get_y_top(pix, width, height, background, difference)
y_bot = get_y_bot(pix, width, height, background, difference)
x_left = get_x_left(pix, width, height, background, difference)
x_right = get_x_right(pix, width, height, background, difference)
对于此图像(白色背景上的鸡蛋):
您可以通过以下步骤进行裁剪:
卵子图像,大小为
(480, 852, 3)
,成本为0.016s
。你知道吗代码:
如果图片的其余部分是一种颜色,您可以比较每个像素,并找到一种不同的颜色来指示图片的开始,例如请注意,我假设右上角是背景色,如果情况并非总是如此,请使用不同的方法(例如计数模式像素颜色)!:
使用此信息,您可以裁剪图像并保存:
因此:
相关问题 更多 >
编程相关推荐