I'd like to get a 1000 x 1000 picture in Python from any input picture so that the input doesn't lost it's aspect ratio. With other words, I want to resize the input so that its longer dimension be 1000 pixels and "fill" the other dimension with the background color until it become 1000 x 1000 square. The original must be in the center at the end.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Building on Alexander-Reynolds answer above, here is the code that handles all possible sizes and situations.
def resizeAndPad(img, size, padColor=255):
Using OpenCV
You can use
resize()
in OpenCV to resize the image up/down to the size you need. However,resize()
requires that you put in either the destination size (in both dimensions) or the scaling (in both dimensions), so you can't just put one or the other in for 1000 and let it calculate the other for you. So the most robust way to do this is to find the aspect ratio and calculate what the smaller dimension would be when the bigger one is stretched to 1000. Then you can resize.Note that if
aspect
is greater than 1, then the image is oriented horizontally, while if it's less than 1, the image is oriented vertically (and is square ifaspect = 1
).Different interpolation methods will look better depending on whether you're stretching the image to a larger resolution, or scaling it down to a lower resolution. From the
resize()
docs:So, after resizing we'll end up with a
1000xN
orNx1000
image (whereN<=1000
) and we'll need to pad it with whatever background color you want on both sides to fill the image to1000x1000
. For this you can usecopyMakeBorder()
for a pure OpenCV implementation, or since you're using Python you can usenumpy.pad()
. You'll need to decide what to do in case an odd number of pixels needs to be added in order to make it1000x1000
, like whether the additional pixel goes to the left or right (or top or bottom, depending on the orientation of your image).Here's a script that defines a
resizeAndPad()
function which automatically calculates the aspect ratio, scales accordingly, and pads as necessary, and then uses it on a horizontal, vertical, and square image:And this gives the images:
Using ImageMagick
ImageMagick
is a simple, but well-built command-line interface to do basic image processing. It's very easy to do what you want with a single command. See here for descriptions of the resizing commands.Producing the images: