裁剪图像,如果没有足够的白色照片区域,请更改黑色区域 [英] Crop image, change black area if not not enough photo region in white

查看:97
本文介绍了裁剪图像,如果没有足够的白色照片区域,请更改黑色区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用PIL使用python裁剪照片.
如果照片区域不足,则该区域的其余部分将被涂成黑色.
我该如何使该区域变白?

I have to crop a photo with python using PIL.
If the photo region is not enough, the rest of the area is colored in black.
How can I make that area white?

这是我现在使用的代码的一部分:

This is a part of the code I`m using now:

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')

收割效果很好,但我要在该区域的其余部分使用白色而不是黑色. 我尝试用白色背景创建新图像并粘贴裁切后的图像,但是没有用.

The crop works fine, but I want white instead of black in the rest of the area. I tried creating a new image with white background and pasting the croped image, but it didn`t work.

示例输出

我有原始图像和裁剪的坐标
我更新了代码
记住作物坐标可能为负.

I have the original image and the coords for the croping
I updated the code
Remeber that the crop coords can be negative.

输入&输出示例
输入img: http://i.imgur.com/vbmPy.jpg

Input & output example
input img: http://i.imgur.com/vbmPy.jpg

box2=(-743, 803, 1646, 4307)  

输出img: http://i.imgur.com/K7sil.jpg

推荐答案

在我看来,您做错了什么,应该共享整个代码和图像.

It looks to me like you're doing something wrong, and that you should share your entire code, and the image.

我在PIL中已经做过很多次了,最简单的解决方案一直是将农作物粘贴到全白图像上.

I've done this many times in PIL , and the easiest solutions has always been to Paste the Crop onto an all-white image.

import Image

# open source
i = Image.open('hHncu.png')

# crop it
( newX , newY ) = ( 110 , 0 )
( newW , newH ) = ( 110 , 150 )
box_crop = ( newX,newY,newX+newW,newY+newH )
i2 = i.crop(box=box_crop)
i2.load()

# save it , just for testing
i2.save('hHncu-out.png')

# create the new image, and paste it in
# note that we're making it 300x300  and have the background set to white (255x3)
i3 = Image.new( 'RGB' , (300,300) , (255,255,255) )
# paste it at an offset. if you put no offset or a box, i3 must match i2s dimensions
i3.paste( i2 , (25,25) )
# save it
i3.save('hHncu-out-2.png')

这篇关于裁剪图像,如果没有足够的白色照片区域,请更改黑色区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆