0

I'm trying to get BGR values from an image using its coordinates. I used a python code to get coordinates of that specific point by clicking it.

import numpy as np
import cv2
def click_event(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print(x,', ' ,y)
        font = cv2.FONT_HERSHEY_SIMPLEX
        strXY = str(x) + ', '+ str(y)
        cv2.putText(img, strXY, (x, y), font, .5, (255, 255, 0), 2)
        cv2.imshow('image', img)
    if event == cv2.EVENT_RBUTTONDOWN:
        blue = img[y, x, 0]
        green = img[y, x, 1]
        red = img[y, x, 2]
        font = cv2.FONT_HERSHEY_SIMPLEX
        strBGR = str(blue) + ', '+ str(green)+ ', '+ str(red)
        cv2.putText(img, strBGR, (x, y), font, .5, (0, 255, 255), 2)
        cv2.imshow('image', img)

img = cv2.imread('img.PNG')
img=cv2.resize(img,(640,640))
cv2.imshow('image', img)

cv2.setMouseCallback('image', click_event)

cv2.waitKey(0)
cv2.destroyAllWindows()

image and coordinates of red and green color

The above program will give coordinates of the mouse clicking point. Then I tried to retrieve the BGR value of that specific coordinates using the following code

import cv2 as cv

image=cv.imread("img.PNG")
image=cv.resize(image,(640,640))
cv.waitKey(0)
color = image[315, 494]
# 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)

The coordinates [315,494] is a red-colored point. But the result is different from red. I got this result

[ 80 208 146]
Faslur Rajah
  • 861
  • 2
  • 10
  • 17
  • @Sid are you sure. I think OpenCV uses BGR ordering – Faslur Rajah Oct 02 '19 at 09:44
  • Yup guys sorry. – Sid Oct 02 '19 at 09:44
  • The output BGR value is nearly green color. But the coordinate [315,494] is pointing out a green color location. I resized the image same size for each code – Faslur Rajah Oct 02 '19 at 09:47
  • 3
    in your example, is [315,494] x = 315 and y = 419 or the other way around? Not sure about numpy, but openCV C++ uses [y,x] ordering. The pixel x=494 and y=315 looks green to me. In your mouseclick event you are using [y,x] ordering. – Micka Oct 02 '19 at 09:57
  • 2
    Oh ! That's the mistake I made. Thank you. Now it's fine with y,x order. It's very helpful – Faslur Rajah Oct 02 '19 at 09:58

0 Answers0