我必须使用 PIL 用 python 裁剪照片。
如果照片区域不够,则其余区域涂成黑色。
我怎样才能使该区域变白?
这是我现在使用的代码的一部分:
i = Image.open(filepath)
box2 = (newX,newY,newX+newW,newY+newH)
i2=i.crop(box=box2)
i2.load()
...
i2.save(new_filepath)
...
white=(255,255,255)
i3 = Image.new( 'RGB' , i2.size , white )
i3.paste( i2)
i3.save(filepath2,'PNG')
裁剪效果很好,但我想在其余区域使用白色而不是黑色。 我尝试创建一个具有白色背景的新图像并粘贴裁剪后的图像,但它不起作用。
编辑: 示例输出
EDIT2:我有原始图像和裁剪坐标
我更新了代码
请记住,裁剪坐标可能为负值。
输入输出示例
输入图片:/image/sKb04.jpg
box2=(-743, 803, 1646, 4307)
输出图片:/image/8TMnZ.jpg
最佳答案
如果你可以使用 numpy,你可以这样做:
i22 = flipud(asarray(i2).copy())
# calculate the area that its black, using the original size and the box information
for i in xrange(blackrows):
i22[i:] = asarray([255,255,255])
# and and something like that to the blackcolumns
我不经常使用 PIL,但它可能有一些像素访问功能。
关于python - 裁剪图像,如果没有足够的白色照片区域,则更改黑色区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12177972/