Resize rectangular image to square, keeping ratio and fill background with black

2024/11/20 1:53:03

I'm trying to resize a batch of grayscale images that are 256 x N pixels (N varies, but is always ≤256).

My intention is to downscale the images.

The resize would have to output a square (1:1) image, with:

  • resized image centered vertically
  • aspect ratio maintained
  • remaining pixels rendered black

Visually this would be the desired result:

enter image description here

I have tried creating a numpy zeroes matrix with the target size (e.g. 200 x 200) but have not been able to paste the resized image into its vertical center.

Any suggestions using cv2, PIL or numpy are welcome.

Answer

You can use Pillow to accomplish that:

Code:

from PIL import Imagedef make_square(im, min_size=256, fill_color=(0, 0, 0, 0)):x, y = im.sizesize = max(min_size, x, y)new_im = Image.new('RGBA', (size, size), fill_color)new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))return new_im

Test Code:

test_image = Image.open('hLarp.png')
new_image = make_square(test_image)
new_image.show()

For a white background you can do:

new_image = make_square(test_image, fill_color=(255, 255, 255, 0))

Result:

enter image description here

https://en.xdnf.cn/q/26369.html

Related Q&A

How to capture arbitrary paths at one route in FastAPI?

Im serving React app from FastAPI by mounting app.mount("/static", StaticFiles(directory="static"), name="static")@app.route(/session) async def renderReactApp(request: Re…

Changing the active class of a link with the twitter bootstrap css in python/flask

I got the following html snippet from my page template.html.<ul class=nav><li class="active"><a href=/>Home</a></li><li><a href=/lorem>Lorem</a>…

overwriting a spark output using pyspark

I am trying to overwrite a Spark dataframe using the following option in PySpark but I am not successfulspark_df.write.format(com.databricks.spark.csv).option("header", "true",mode=…

How to patch a constant in python

I have two different modules in my project. One is a config file which containsLOGGING_ACTIVATED = FalseThis constant is used in the second module (lets call it main) like the following:if LOGGING_ACTI…

Python script for minifying CSS? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Saving numpy array to txt file row wise

I have an numpy array of forma = [1,2,3]which I want to save to a .txt file such that the file looks like:1 2 3If I use numpy.savetxt then I get a file like:1 2 3There should be a easy solution to this…

I want Python argparse to throw an exception rather than usage

I dont think this is possible, but I want to handle exceptions from argparse myself.For example:import argparse parser = argparse.ArgumentParser() parser.add_argument(--foo, help=foo help, required=Tru…

Pass Variable from python (flask) to HTML in render template?

The web server works (python flask) but when I go to the website, where the value of animal should be (dog) it shows the variable name animal. (There is more to the code but this is the most simplistic…

How to clear console in sublime text editor

How to clear console in sublime text editor. I have searched on internet too..But cant find proper shortcut for that. Please provide info

YAML loads 5e-6 as string and not a number

When I load a number with e form a JSON dump with YAML, the number is loaded as a string and not a float.I think this simple example can explain my problem.import json import yamlIn [1]: import jsonIn …