Skip to content
Advertisement

Getting the colour of a particular pixel with opencv

I’m trying to determine the colour of a single pixel in an image using Python and OpenCV. However, when I read the BGR values from that pixel and use those same values to draw a circle back on the image, the colours do not match. Where am I going wrong?

import cv2

def get_bgr(filename):
    image = cv2.imread(filename)
    target = [int(image.shape[1] / 2), int(image.shape[0] / 2)]

    b, g, r = image[target[0], target[1]]
    image = cv2.circle(image, [target[0], target[1]], 5, (int(b), int(g), int(r)), 2)

    print(f'colour = {b}, {g}, {r}')

    cv2.imshow('image', image)
    cv2.waitKey(0)

if __name__ == '__main__':
    get_bgr('shapes.jpg')

Output:

Note the cyan circle drawn on the yellow rectangle in the centre of the image. I would have expected this circle to match the shape beneath.

colour = 172, 186, 8

the image shown by imshow()

Advertisement

Answer

The problem you have here is that you mixed x and y coordinates.
image has (y, x) so the point you took colors from is y,x.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement