简体   繁体   中英

How to get the pixel indices of a specific RGB value of a image in python?

I have imported a color image using openCV imread function.

im = cv2.imread('test.jpg')

I am looking to find the indices of white pixels, which have a pixel value of [255, 255, 255]. I know im is actually a 3D array. But what is weird is the value of im[0,0] is [255 255 255], rather than [255, 255, 255]. And im[0,0,0] is 255. So [255 255 255] seems like a list or something, but actually not equivalent to [255, 255, 255].

>>> print im[0,0]
[255 255 255]

>>> print im[0,0,0]
255

So my questions are:

  1. What is the difference between [255 255 255] and [255, 255, 255]?
  2. How can I get the indices of all withe pixels? What search algorithm should I use?

If you want to get the indices of all white pixels, you can convert your image into a 2D array and then find the indices

import operator

image = cv2.imread("test.jpg")
img = image.astype('float')
img = img[:,:,0] # convert to 2D array
row, col = img.shape
for i in range(row):
    for j in range(col):
        if img[i,j] == 255:
            x.append(i) # get x indices
            y.append(j) # get y indices

Note that image[0,0] shows 2D matrix whereas image[0,0,0] shows a 3D matrix with 0-color band. This element basically defines the color band of the image. If you do not specify third element, it will show you three values for each color band of the image. But when you mention the color band, it will show you the exact pixel value.

NOTE: There is no need to convert the image into a 2D array. you can always do it for the actual array too. I did so to simply explain the algorithm to you.

You are right neuxx. the value [255 255 255] is not equal to [255, 255, 255]. so you need to convert pixel value ( [255 255 255] ) into array value( [255, 255, 255] ) to compare. so you need to use '[:]' to convert it to array. Moreover, if you want to find all white pixels you can use this code. While pixel indices will be stored in the list "White_pix_ind" as a tuple.

White_pix_ind = []
row,col,depth = Img.shape
for i in range(row):
    for j in range(col):
        if( (Img[(i,j)][:]==White_pix_ind ).all() ):
            print(i,j)
            White_pix_ind.append((i,j))
            break;

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