Anıl Akdemir
Anıl Akdemir

Reputation: 11

How can i get the RGB values of an image as numpy array using OpenCV, Python

I need to RGB values of an image using OpenCV, but when I read an image as below, sometimes it does not return exact values.

    import cv2
    img = cv2.imread('camel.jpeg')

For example

For this picture ( camel.jpg ) everything is correct but for this picture (result.jpg) it returns 255 for every pixel. But if try to read a specific pixel, I can reach the RGB value of the pixel. I tried to use a for loop but the result was not correct, it returned again 255 for every pixel. What should i do?

Upvotes: 1

Views: 4694

Answers (2)

Swayam
Swayam

Reputation: 11

I used Pillow for this and it worked perfectly fine

from PIL import Image
import numpy as np

img = Image.open('camel.jpeg')
img_array = np.array(img)

print(img_array.shape)
print(img_array)

Result

(1477, 1200, 3)

[[[105 159 206]
  [106 160 207]
  [106 160 207]
  ...
  [215 215 217]
  [215 215 217]
  [216 216 218]]

 [[105 159 206]
  [106 160 207]
  [106 160 207]
   ...

It works fine and as you can say the shape of img_array also matched with resolution of camel.jpeg

Upvotes: 1

fmw42
fmw42

Reputation: 53174

I did this on your camel image in Python/OpenCV to get two pixels. Channel values are not just 0 and 255.

import cv2
import numpy as np

# load image and get dimensions
img = cv2.imread("camel.jpg")
hh, ww = img.shape[:2]

# get pixel at x=0,y=0
px1 = img[0:1, 0:1]

# get pixel at center of image
hh2 = hh//2
ww2 = ww//2
px2 = img[hh2:hh2+1, ww2:ww2+1]

print(px1)
print(px2)

Results:

[[[0 0 0]]]
[[[129   0 193]]]

But you should be able to just print(img) or use Numpy to crop a region and print it.

Perhaps there is something wrong with your camel.jpeg image, but it gets fixed when saving and posting it. Try uploading the file you posted and see if it has the same issue.

Upvotes: 1

Related Questions