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.
EDIT: example output
EDIT2: I have the original image and the coords for the croping
I updated the code
Remeber that the crop coords can be negative.
Input & output example
input img: http://i.imgur.com/vbmPy.jpg
box2=(-743, 803, 1646, 4307)
output img: http://i.imgur.com/K7sil.jpg
To do exactly as you asked, convert the image to a numpy array and filter the full black rows and cols (on a second image). You can't simply make all the black pixels white, as this would affect those on the inside of the image.
It looks like there is some smoothing between the black and the image, a more advanced filter would be needed to fix this - but you can see how to get started from here!
ok. so here's a quick stab at the idea i mentioned.
the rebox() function returns a 'fixed' bounding box, along with some offset data
this works in most situations. i didn't integrate the offset data , but some version of it it would probably go in the
i3.paste
section.the test image, grid.png is 300x300 and has blue lines at 50px, red lines at 150px and green lines at 200px.
you should be able to tweak this to your exact needs.
If you can use numpy, you could do something like:
I don't use PIL a lot, but it probably has some pixel acessing functions.
It looks to me like you're doing something wrong, and that you should share your entire code, and the image.
I've done this many times in PIL , and the easiest solutions has always been to Paste the Crop onto an all-white image.