python - 裁剪图像,如果没有足够的白色照片区域,则更改黑色区域

标签 python python-imaging-library

我必须使用 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')

裁剪效果很好,但我想在其余区域使用白色而不是黑色。 我尝试创建一个具有白色背景的新图像并粘贴裁剪后的图像,但它不起作用。

编辑: 示例输出

example output

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/

相关文章:

python - 你能编写一个针对任意状态的 django-fsm 转换吗?

python - 使用 OpenCV 将一定范围内的颜色更改为另一种颜色

python - PIL 透明背景中的残留白色像素

python - 打印图像时,什么决定了它在页面上的显示大小?

python - Python 中的 mkdir -p 功能

python - GUI 表单编辑器

python - SIFT feature_matching点坐标

python - 仅使用 AWS Lambda 加载本地模块时出现问题

python - 在 Google 云存储桶中使用 PIL 更改图像大小(从 GCloud 中的虚拟机)

python - 类型错误 : unsupported operand type(s) for -: 'tuple' and 'tuple'