In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to resize the image in Python, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Create Ima
In this example, we will create our own image instead of finding a real image to manipulate.
Why? In fact, creating an image is a good way to show what an image actually is. This resizing program also works on Instagram.
So, what is an image? In Python data terminology, an image is a list of int tuples.
Image = list [list [tuple [* int, float]
NumPy is defined as a two-dimensional shape array (h, w, 4), where h represents the number of high pixels (top and bottom) and w represents the number of wide pixels (from left to right).
In other words, an image is a list of pixels (rows) (the entire image). Each pixel consists of 3 integers and an optional floating point number: red channel, green channel, blue channel, alpha (floating point optional). The red, green, and blue channels (RGB) have values from 0 to 255.
From now on, we will discuss color images without alpha channels to keep them simple. Alpha is the transparency of pixels. An image can also have only one channel with values from 0 to 255. This is the grayscale image, that is, the black and white image. We use color images here!
Import matplotlib as pltpixel: tuple = (200100150) plt.imshow ([[list (pixel)]])
Making images with pure Python
Python is fully capable of creating images. To display it, I will use the matplotlib library, which you can use to install:
Pip install matplotlib
Create pixels:
From dataclasses import dataclass@dataclassclass Pixel: red: int green: int blue: int # alpha: float = 1 pixel = Pixel) pixel# returns: # Pixel (red=255, green=0, blue=0, alpha=1)
Create an image:
From _ _ future__ import annotationsfrom dataclasses import dataclass, astuplefrom itertools import cyclefrom typing import Listimport matplotlib.pyplot as pltimport matplotlib.image as mpimg@dataclassclass Pixel: red: int green: int blue: int # alpha: float = 1pixel = Pixel (255Power0) pixelmarigold: Pixel = Pixel (234) red: Pixel = Pixel (255Power0) Image = list [pixel] def create_image (* colors: Pixel, blocksize: int = 10 Squaresize: int = 9)-> Image: make a square image with configurable blocks of pixels (same width and height). Args: colors (Pixel): a parameter that iterates through the color rendering order. Blocksize (int, optional): [description]. Default 10. Squaresize (int, optional): [description]. Default 9. Returns: Image: a beautiful square picture! "" Img: list = [] colors = cycle (colors) for row in range (squaresize): row: list = [] for col in range (squaresize): color = next (colors) # set color for _ in range (blocksize): values: list [int] = list (astuple (color) row.append (values) [img.append (row) for _ in range (squaresize)] # create row height Return imgif _ _ name__ = ='_ main__': image = create_image (marigold Red) plt.imshow (image)
This is the rendered image. Behind the scenes, the data looks like this:
[234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [234, 162, 33],...
Now that we have an image, let's resize it!
Resize in Python
Writing algorithms for resizing images in Python actually requires a lot of work.
There are many contents in the image processing algorithm, and some people have contributed a lot of work to it. For example, resampling-a pixel is used to represent the surrounding high-resolution pixels in a scaled-down image. Image processing is a huge topic. If you want to see for yourself, look at Pillow's Image.py, which is in the path path/to/site-packages/PIL.
There are also some optimizations, such as anti-aliasing and gap reduction. There is a lot of content here. We stand on the shoulders of giants and can solve our problems with a single line of code.
If you are interested in learning more about what happens behind the scenes when working with images, I encourage you to look more at the "machine vision" topic! This is definitely a booming area.
If you do well enough, many companies will be willing to pay the highest price for your computer vision expertise. Autopilot, IOT, surveillance, you name it; all basically depends on processing images (usually on Python or C++).
A good starting point is to look at the scikit image.
OpenCV
OpenCV can be used for image processing. He wrote it in C++ and ported it to Python.
Import cv2def resize (fp: str, scale: Union [float, int])-> np.ndarray: "" resize the image to maintain its ratio Args: fp (str): the path parameter scale (Union [float, int]): percentage of the image file as a parameter. For example: 53 Returns: image (np.ndarray): scaled-down picture "" _ scale = lambda dim, s: int (dim * s / 100) im: np.ndarray = cv2.imread (fp) width, height, channels = im.shape new_width: int = _ scale (width, scale) new_height: int = _ scale (height, scale) new_dim: tuple = (new_width, new_height) return cv2.resize (src=im) Dsize=new_dim, interpolation=cv2.INTER_LINEAR)
The option for the interpolation parameter is one of the flags provided in the cv2 package:
INTER_NEAREST-nearest neighbor interpolation INTER_LINEAR-Bilinear interpolation (default) INTER_AREA-resampling using pixel region relationships. It may be the preferred method of image extraction. But when the image is scaled, it is similar to the INTER_NEAREST method. INTER_CUBIC-a bicubic interpolation INTER_LANCZOS4 greater than 4 × 4 pixel neighborhood-a Lanczos interpolation greater than 8 × 8 pixel neighborhood
After returning:
Resized = resize ("checkers.jpg", 50) print (resized.shape) plt.imshow (resized) # can also use cv2.imshow ("name", image)
It did what we expected. The image ranges from 900 pixels high and 900 pixels wide to 450 × 450 (there are still three color channels). The screenshot above doesn't look good because of Jupyter Lab's matplotlib coloring.
Pillow
The pillow library has a resizing method on the Image class. Its parameters are:
Size: (width, height) resample: default is BICUBIC. The parameters required by the resampling algorithm. Box: the default is None. Is a 4-tuple that defines the image rectangle that works within the parameter (0J0, width, height). Reducing_gap: the default is None. Resample the optimization algorithm to make the output look better.
Here are the functions:
From PIL import Imagedef resize (fp: str, scale: Union [float, int])-> np.ndarray: "" resize the image to maintain its ratio Args: fp (str): the path parameter scale (Union [float, int]): percentage of the image file as a parameter. For example: 53 Returns: image (np.ndarray): scaled-down picture "" _ scale = lambda dim, s: int (dim * s / 100) im = Image.open (fp) width, height = im.size new_width: int = _ scale (width, scale) new_height: int = _ scale (height, scale) new_dim: tuple = (new_width, new_height) return im.resize (new_dim)
The functions that use Pillow are very similar to OpenCV. The only difference is that the PIL.Image.Image class has the property size used to access the image (width, height).
The result is:
Resized = resize ("checkers.jpg", 30.5) print (resized.size) resized.show ("resized image", resized)
Notice how the show method opens the operating system's default program to view the file type of the image.
Create a command line program
Now that we have a resizing function, it's time for it to have a user interface that runs resizing.
It is possible to resize an image. But we want to be able to process images in bulk.
The interface we are going to build will be the simplest: the command line utility.
The Pallets project is the genius community behind Flask and is a Jinja template engine: Click (https://click.palletsprojects.com/en/7.x/.)
Pip install click
Click is a library for making command-line programs. This is much better than using normal argparse or starting some if-then logic in if _ _ name__ ='_ _ main__':. So, we will use Click to decorate our image adjuster.
Here is a complete script for resizing the image from the command line!
"resize.py" from _ future__ import annotationsimport osimport globfrom pathlib import Pathimport sysimport clickfrom PIL import Image "" document: https://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html"""SUPPORTED_FILE_TYPES: list [str] = [".jpg", ".png"] def name_file (fp: Path, suffix)-> str: return f "{fp.stem} {fp.suffix}" def resize (fp: str) Scale: Union [float, int])-> Image: "" resize the image Keep its ratio Args: fp (str): the path parameter scale (Union [float, int]): percentage of the image file as a parameter. For example: 53 Returns: image (np.ndarray): scaled-down image "" _ scale = lambda dim, s: int (dim * s / 100) im: PIL.Image.Image = Image.open (fp) width, height = im.size new_width: int = _ scale (width, scale) new_height: int = _ scale (height, scale) new_dim: tuple = (new_width) New_height) return im.resize (new_dim) @ click.command () @ click.option ("- p", "--pattern") @ click.option ("- s", "--scale", default=50, help= "Percent as whole number to scale. Eg. 40 ") @ click.option ("-Q ","-- quiet ", default=False, is_flag=True, help=" Suppresses stdout. ") def main (pattern: str, scale: int, quiet: bool): for image in (images: = Path (). Glob (pattern): if image.suffix not in SUPPORTED_FILE_TYPES: continue im = resize (image, scale) nw Nh = im.size suffix: str = f "_ {scale} _ {nw} x {nh}" resize_name: str = name_file (image, suffix) _ dir: Path = image.absolute (). Parent im.save (_ dir / resize_name) if not quiet: print (f "resized image saved to {resize_name}.") If images = []: print (f "No images found at search pattern'{pattern}'.") Returnif _ _ name__ = ='_ _ main__': main ()
The command line program runs from the entry point function main. Parameters are passed to the click.option option:
Pattern uses strings to locate one or more images related to the directory in which the script runs. -- pattern= ".. / catpics/*.png will look up the catpics folder and return all files in that folder with the .png image extension.
Scale takes a number, floating point, or integer and passes it to the resize function. This script is simple and has no data validation. If you add to the code, check that the scale is a number between 5 and 99 (a reasonable downscaling parameter). You can set it through-s "chicken nuggets".
Quiet is an option parameter if you do not want to output text to a standard stream while the program is running.
Run the program from the command line:
Python resize.py-s 35-p ". / * jpg"
Results:
$py resize.py-p "checkers.jpg"-s 90resized image saved to checkers_90_810x810.jpg.
Checking folders:
$ls-lh checkers*-rw-r--r-- 1 nicho 197609 362K Aug 15 13:13 checkers.jpg-rw-r--r-- 1 nicho 197609 231K Aug 15 23:56 checkers_90_810x810.jpg
Good! So the program shrinks the image, gives it a descriptive label, and we can see that the file size ranges from 362KB to 231KB!
To see that the program processes multiple files at the same time, we will run it again:
Py resize.py-- pattern= "checkers*"-- scale=20resized image saved to checkers_20_180x180.jpg.resized image saved to checkers_90_810x810_20_162x162.jpg.
File system output:
$ll-h checkers*-rw-r--r-- 1 nicho 197609 362K Aug 15 13:13 checkers.jpg-rw-r--r-- 1 nicho 197609 1.8K Aug 16 00:23 checkers_20_180x180.jpg-rw-r--r-- 1 nicho 197609 231K Aug 15 23:56 checkers_90_810x810.jpg-rw-r--r-- 1 nicho 197609 1.8K Aug 16 00:23 checkers_90_810x810_20_162x162.jpg
As long as the pattern is matched, recursion can process any number of images.
Click
Click is a magical tool. It can wrap a function and run it "normally" from an if _ _ name__ = ='_ _ main__' statement in a module. (in fact, it doesn't even need to do this; you just need to define and decorate the functions to run), but its real highlight is to install scripts as packages.
This is done through the setuptools library that ships with Python.
This is my setup.py.
From setuptools import setupsetup (name='resize', version='0.0.1', py_modules= ['resize'], install_requires= [' click', 'pillow',], entry_points=''' [console_scripts] resize=resize:main'')
Generate an executable file / wrapper using the following command:
Pip install-e.
You can now invoke the script without using the python command. In addition, if you add a new executable to a folder in the path, you can call this program from anywhere on your computer, such as resize-p * jpg-s 75
After reading the above, do you have any further understanding of how to resize the image in Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.