Home > Mobile >  How to get pixel rgb values using matplotlib?
How to get pixel rgb values using matplotlib?

Time:12-21

I need to find all red pixels in an image and create my own image with just the red pixels. So far I have been experimenting with matplotlib as I am very new to it.

def find_red_pixels(map, upper_threshold=100, lower_threshold =50):
    """Finds all red pixels of the "map" image and outputs a binary image file "map-red-pixels.jpg" """
    red_map = []
    for row in map:
        for pixel in row:
            print(pixel)

I am brand new to image manipulating and have tried this, however I do not understand what the values [0.0.01] etc. mean which is outputted as pixels. Is there an easy way to do this?

CodePudding user response:

The first thing to understand is the way the image is represented in an array when it is read in. Here I read in a 320x160 image of a rainbow:

enter image description here

>>> img = plt.imread('rainbow.png')
>>> img.shape
    (160, 320, 4)

This shows the dimensions of the array - note the last element of the tuple is 4. These values represent the red pixel values, the green pixel values, the blue pixel values, and the transparency or alpha values.

We want to find pixels which have a certain red value, so we're just interested in the first of these. Let's split these out so we can just work with them:

>>> r = img[:,:,0]

This isolates the portion of the array relating to the redness of the pixel values, represented by a value between 0 and 1. We now want to isolate the locations of the pixels which have a certain redness value. We can use enter image description here

  • Related