Search code examples
pythonimageopencvpython-imaging-libraryscikit-image

How to select region on image and extract pixel values in numbers of that particular region?


I want to select a rectangular region on the image using mouse events and extract the pixel values within the rectangle as a list or an array or a tuple but not an image crop that returns a cropped image. I have found no way of how to achieve this.

Does anyone know any way of achieving this or any tips or suggestions?

Thank you so much for reading.


Solution

  • The function to use is cv.selectROI

    It can take different arguments. The simplest case is just taking an image (numpy array). Here's an example where also the window name is specified.

    Personally I also prefer to use the fromCenter argument.

    import numpy as np
    import cv2 as cv
    
    im = cv.imread(cv.samples.findFile("lena.jpg"))
    
    bbox = cv.selectROI("lena", im, fromCenter=True)
    cv.destroyWindow("lena")
    
    print("region:", bbox)
    
    (x,y,w,h) = bbox
    
    subregion = im[y:y+h, x:x+w]
    cv.imshow("lena subregion", subregion)
    cv.waitKey(-1)
    cv.destroyWindow("lena subregion")