"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Handle RGB Pixel Manipulation in Python: Retrieving and Assigning Values

How to Handle RGB Pixel Manipulation in Python: Retrieving and Assigning Values

Published on 2024-11-04
Browse:665

How to Handle RGB Pixel Manipulation in Python: Retrieving and Assigning Values

Retrieving and Modifying RGB Pixel Values in Python

Retrieving RGB Values

To obtain the RGB values of a specific pixel with coordinates (x, y) from an image loaded with open("image.jpg"), you can use the Python Image Library (PIL). Here's how:

from PIL import Image

im = Image.open('image.jpg')
pix = im.load()
rgb_values = pix[x, y]

The rgb_values variable will be a tuple containing the Red, Green, and Blue values.

Writing Pixels

To create a pixel with a given RGB value on a blank graphic, you can again use PIL. Here's a simple example:

from PIL import Image
import numpy as np

# Create a new blank image
img = np.zeros((500, 500, 3), dtype=np.uint8)
img[200, 200] = [255, 0, 0]  # Set the pixel at coordinates (200, 200) to red

# Create an Image object from the array
im = Image.fromarray(img)

# Save the image as a PNG
im.save('test.png')

Note: PIL is an external library that needs to be installed separately to use this solution.

Release Statement This article is reprinted at: 1729170797 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3