好的。所以这里是我提到的想法的快速尝试。
rebox() 函数返回一个“固定”边界框,以及一些偏移数据
这在大多数情况下都有效。我没有整合偏移数据,但它的某些版本可能会放在该i3.paste
部分中。
测试图像 grid.png 为 300x300,蓝线为 50 像素,红线为 150 像素,绿线为 200 像素。
您应该能够根据您的确切需求进行调整。
import Image
i1 = Image.open('grid.png')
DEBUG = True
def rebox( box_original , box_crop_desired ):
box_crop_new= list( box_crop_desired )
box_crop_offset = [ 0 , 0 ]
if box_crop_desired[0] < 0:
box_crop_new[0] = 0
box_crop_offset[0] = box_crop_desired[0]
if box_crop_desired[1] < 0:
box_crop_new[1] = 0
box_crop_offset[1] = box_crop_desired[1]
if box_crop_desired[2] > box_original[2]:
box_crop_new[2] = box_original[2]
if box_crop_desired[3] > box_original[3]:
box_crop_new[3] = box_original[3]
box_crop_offset = tuple(box_crop_offset)
box_crop_new = tuple(box_crop_new)
if DEBUG :
print "box_original %s" % str(box_original)
print "box_crop_offset %s" % str(box_crop_offset)
print "box_crop_desired %s" % str(box_crop_desired)
print "box_crop_new %s" % str(box_crop_new)
return ( box_crop_new , box_crop_offset )
( newX , newY ) = ( 200 , 200 )
( newW , newH ) = ( 400 , 400 )
box_crop_desired = ( newX , newY , newX+newW, newY+newH )
( box_crop , box_crop_offset ) = rebox( i1.getbbox() , box_crop_desired )
i2 = i1.crop(box=box_crop)
i2.save('grid-out-b.png')
i3 = Image.new( 'RGBA' , ( newW , newH ) , (255,255,255) )
i3.paste( i2 , (0,0) )
i3.save('grid-out-final-b.png')