Home >Backend Development >Python Tutorial >How to use Python to perform pixel-level operations on images
How to use Python to perform pixel-level operations on pictures
In the development of modern technology, we often need to perform various operations and processing on pictures. For some special image processing needs, pixel-level operations are a common method. In this article, we will introduce how to use Python to perform pixel-level operations on images, with corresponding code examples.
from PIL import Image import numpy as np import matplotlib.pyplot as plt
img = Image.open("image.jpg") img.show()
getdata()
method and convert it into a NumPy array. pixels = np.array(img.getdata()).reshape(img.size[1], img.size[0], 3)
In the above code, the getdata()
method returns a one-dimensional array containing the pixel values of the image. We convert it into a three-dimensional array through the reshape()
method, where the first dimension represents the height of the image, the second dimension represents the width of the image, and the third dimension represents the number of channels of the image.
gray_img = np.mean(pixels, axis=2).astype(np.uint8) plt.imshow(gray_img, cmap="gray") plt.show()
invert_img = 255 - pixels plt.imshow(invert_img) plt.show()
from scipy.ndimage.filters import convolve kernel = np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]]) blurred_img = convolve(pixels, kernel) plt.imshow(blurred_img.astype(np.uint8)) plt.show()
result_img = Image.fromarray(blurred_img.astype(np.uint8)) result_img.save("result.jpg")
Through the above steps, we can use Python to perform pixel-level operations on the image and save the result as a new image file. Not only that, we can also customize various pixel-level operations according to needs and implement them through code. I hope this article can provide some help and inspiration for your work and study in image processing.
Summary:
This article introduces how to use Python to perform pixel-level operations on images. We open and display images by importing the PIL library, NumPy library and Matplotlib library. Then, obtain the pixel values of the image and perform pixel-level operations on the image, such as grayscale, inversion, and Gaussian blur. Finally, save the processed image. Through these steps, we can process images flexibly and implement a variety of image processing needs.
The above is the detailed content of How to use Python to perform pixel-level operations on images. For more information, please follow other related articles on the PHP Chinese website!