load image and modify specific pixel data in python

To load and modify specific pixel data of an image in Python, you can use the Python Imaging Library (PIL). Here's how to do it:

  1. Install PIL using the following command:
main.py
!pip install Pillow
20 chars
2 lines
  1. Import the necessary libraries:
main.py
from PIL import Image
import numpy as np
41 chars
3 lines
  1. Load the image using the Image.open() function:
main.py
img = Image.open('/path/to/image.jpg')
39 chars
2 lines
  1. Convert the image to a numpy array using np.array() function:
main.py
img_arr = np.array(img)
24 chars
2 lines
  1. Modify the desired pixel data. For example, to change the pixel at coordinates (x, y) to red:
main.py
img_arr[y,x,0] = 255  # set red channel
img_arr[y,x,1] = 0    # set green channel
img_arr[y,x,2] = 0    # set blue channel
123 chars
4 lines
  1. Convert the numpy array back to PIL Image using the Image.fromarray() function:
main.py
img = Image.fromarray(img_arr)
31 chars
2 lines
  1. Save the modified image using the Image.save() function:
main.py
img.save('/path/to/new/image.jpg')
35 chars
2 lines

Overall, these steps can be combined into a function that loads, modifies and saves the image:

main.py
from PIL import Image
import numpy as np

def modify_pixel_image(img_path, pixel_pos, color):
    img = Image.open(img_path)
    img_arr = np.array(img)
    y, x = pixel_pos
    img_arr[y,x,0] = color[0]  # set red channel
    img_arr[y,x,1] = color[1]  # set green channel
    img_arr[y,x,2] = color[2]  # set blue channel
    img = Image.fromarray(img_arr)
    img.save('/path/to/new/image.jpg')
398 chars
13 lines

This function takes the path of the image, the position of the pixel to modify, and the desired color as input. It then modifies the pixel data and saves the new image.

gistlibby LogSnag