简体   繁体   中英

How to get pixel rgb values using matplotlib?

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?

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:

在此处输入图像描述

>>> 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 np.where for this, finding the elements in our new array r which have values of over 0.5 (this value can be altered to fit your requirements of upper_threshold and lower_threshold ), and replacing these with a value of 1 , and 0 otherwise; creating a binary image.

>>> binary_img = np.where(r > 0.5, 1, 0)

Finally, we just need to save this image, using plt.imsave :

>>> plt.imsave('rainbow_red.png', binary_img , cmap='gray')

Giving the following result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM