Search code examples
pythonopencvimage-processingscikit-image

Finding contours and midpoints of color squares in an image


I have an image with color squares in it:

Image of the squares

I am trying find contours for the color squares, as well as the midpoints of the color squares to find the pixel value.


Solution

  • You can use HSV colour space, but you have to pick a range of colour by hand.

    change the H value based on colour and keep the entire range of 0-255 for both S and V or you can limit these as well to be more specific.

    Then you can use contours to draw a bounding box around the detected contour and find the centre.

    Here's the code

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    img = cv2.imread('UQjNf.jpg')
    
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    
    bi = np.zeros((hsv.shape[:2]),np.uint8)
    
    bi[np.where((((hsv <= [20,255,255]) & (hsv >= [20,0,0])) | (hsv <= [21,255,255]) & (hsv >= [21,0,0]) | ((hsv <= [22,255,255]) & (hsv >= [22,0,0])) ).all(axis = 2))] = [255]
    
    plt.imshow(bi)
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()
    

    Here's one such colour that came out nicely enter image description here

    Hope it helps.