extract image data in python

To extract image data in Python, we can use the Python Imaging Library (PIL) and the numpy library.

First, we need to open the image using the Image module from PIL:

main.py
from PIL import Image

img = Image.open('image.jpg')
53 chars
4 lines

Once we have opened the image, we can use the load() method to get the pixel values of the image:

main.py
pixels = img.load()
20 chars
2 lines

The pixels variable now contains a 2D array of tuples, where each tuple represents the RGB values of the corresponding pixel.

We can also convert the image to a numpy array using the numpy library:

main.py
import numpy as np

img_data = np.asarray(img)
47 chars
4 lines

The img_data variable now contains a 3D array where each element represents the RGB values of a corresponding pixel.

We can access and modify individual pixels by indexing the pixel array. For example, to get the RGB values of the pixel at position (x, y), we can use:

main.py
r, g, b = pixels[x, y]
23 chars
2 lines

To set the RGB values of the pixel at position (x, y), we can use:

main.py
pixels[x, y] = (r_new, g_new, b_new)
37 chars
2 lines

Once we have extracted the image data, we can apply any desired processing or analysis.

gistlibby LogSnag