I am loading an image into python e.g.
image = cv2.imread(\"new_image.jpg\")
How can i acccess the RGB values of image
?
You can use numpy Better convert the image into numpy array and transpose the matrix [R G B] will be [B G R] and vice versa
Get B G R color value of pixel in Python using opencv
import cv2
image = cv2.imread("sample.jpg")
color = int(image[300, 300])
# if image type is b g r, then b g r value will be displayed.
# if image is gray then color intensity will be displayed.
print color
output: [ 73 89 102]
You can do
image[y, x, c]
or equivalently image[y][x][c]
.
and it will return the value of the pixel in the x,y,c
coordinates. Notice that indexing begins at 0
. So, if you want to access the third BGR (note: not RGB) component, you must do image[y, x, 2]
where y
and x
are the line and column desired.
Also, you can get the methods available in Python for a given object by typing dir(<variable>)
. For example, after loading image
, run dir(image)
and you will get some usefull commands:
'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', ...
Usage: image.mean()
It worked for me well :
import cv2
import numpy as np
cap = cv2.imread('/home/PATH/TO/IMAGE/IMG_0835.jpg')
#You're free to do a resize or not, just for the example
cap = cv2.resize(cap, (340,480))
for x in range (0,340,1):
for y in range(0,480,1):
color = cap[y,x]
print color`
This code will print the red , green and blue value of pixel 300, 300:
img1 = cv2.imread('Image.png', cv2.IMREAD_UNCHANGED)
b,g,r = (img1[300, 300])
print (r)
print (g)
print (b)