Home > front end >  How to find center pixel value of bounding box in opencv python?
How to find center pixel value of bounding box in opencv python?

Time:11-22

I'm trying to find the pixel intensity at the center of bounding box

TO achieve this I'm finding the center coordinates of bounding box and get the pixel intensity of that coordinate as shown below

img_read= cv2.imread(r'image.png')
cv2.rectangle(img_read,(xmin,ymin),(xmax,ymax),(0,0,255),3)
center_x = int((xmin xmax)//2)
center_y = int((ymin ymax)//2)
print(center_x,center_y)
cv2.circle(img_read,(center_x,center_y),50,(0,0,255),3)
print('Pixel intensity at:',img_read[center_x][center_y])
plt.imshow(img_read[:,:,::-1])

when I run this I get error as below

IndexError: index 859 is out of bounds for axis 0 with size 815

but when I try to draw circle from that point with cv2.circle it draws circle without any errors How can I access the pixel intensity value at point img_read[center_x][center_y]) ? I tried with this as well img_read[center_x,center_y] but got same error

any help or suggestion to fix this issue will be appreciated thanks

CodePudding user response:

#Read the image & get the dimensions  
    img_read= cv2.imread(r"C:\Users\Desktop\test_center_px.tiff")
    dimensions = img_read.shape
    h, w=dimensions[0], dimensions[1]            

#create the bounding box if necessary (not in mine)       
    domain = cv2.rectangle(img_read,(0,0),(w,h),(255,0,0),20)
    plt.imshow(domain,cmap='gray')
    
    center_x = w/2
    center_y = h/2

#all we need to do is pass in the (x, y)-coordinates as image[y, x]
    (b, g, r) = img_read[np.int16(center_y), np.int16(center_x)]
    print("Color at center pixel is - Red: {}, Green: {}, Blue: {}".format(r, g, b))

OUTPUT: Color at center pixel is - Red: 152, Green: 152, Blue: 152

CodePudding user response:

Try:

img_read[center_y,center_x] 
  • Related