Home > Article > Backend Development > How to change image dimensions and size using Python
How to use Python to change the size and size of pictures
Introduction:
In many application scenarios, we may need to change the size and size of pictures to adapt to different needs. Python provides a wealth of libraries to process and manipulate images, allowing us to easily adjust the size and size of images. This article will introduce how to use Python to change the size and shape of images, and provide code examples for readers' reference.
First, we need to install the PIL library. Enter the following command in the command line:
pip install Pillow
After the installation is complete, we can use the following code to change the size of the image:
from PIL import Image # 打开原始图片 img = Image.open('image.jpg') # 设置新的尺寸 new_size = (800, 600) # 调整尺寸 resized_img = img.resize(new_size) # 保存调整后的图片 resized_img.save('resized_image.jpg')
In the code example, we first use Image. The open()
method opens the original image. Then, define a new dimension, specifying the adjusted width and height. Use the resize()
method to resize the original image to the new size and save the adjusted image to the specified file.
Using OpenCV to change the size and shape of images usually requires installing the opencv-python
library. Enter the following command in the command line:
pip install opencv-python
Then, we can use the following code to change the size of the image:
import cv2 # 读取原始图片 img = cv2.imread('image.jpg') # 设置新的尺寸 new_size = (800, 600) # 调整尺寸 resized_img = cv2.resize(img, new_size) # 保存调整后的图片 cv2.imwrite('resized_image.jpg', resized_img)
In the code example, we first use cv2.imread( )
method to read the original image. Then, define a new dimension, specifying the adjusted width and height. Use the cv2.resize()
method to resize the original image to the new size, and use the cv2.imwrite()
method to save the adjusted image to the specified file.
Summary:
This article introduces how to use Python to change the size and size of images. We can use PIL library or OpenCV library to achieve this functionality. By resizing and resizing images, we can easily adapt to different needs and improve our image processing and computing capabilities. Hope this article is helpful to readers!
The above is the detailed content of How to change image dimensions and size using Python. For more information, please follow other related articles on the PHP Chinese website!