Detect areas and their color on an image with Python

Viewed 599

I have an image of a 7 segment display. I want to keep track of the color of each segment. As a starting point, I have created a program where I detect the edges of the segments with the Canny edge detection of OpenCV. I also have obtained the location of these edges.

My problem is that I don't know how to detect those areas that are inside the edges and obtain their color. Here, I post my program code:

import cv2
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt

def size(name):
    """ Print width and height and return value """
    img = Image.open(name)
    width, height = img.size
    total=width*height
    print('Width=%s, Height=%s, Total=%s pixels'%(width, height,total))
    return width, height

def canny_edge_detection(name,minval,maxval):
    """ Edge detection function """
    image=cv2.imread(name)
    canny=cv2.Canny(image, minval, maxval)
    arrayimage=Image.fromarray(canny)
    cannylist=canny.tolist()
    return cannylist, image, canny

def edge_coordinates(pixel_list,color):
    """ Obtain the coordinates of each pixel of the edges to a list(i,j) """
    edgelocationlist=[]
    for i in range(0,height):
        rowpixels=edgepixels[i]
        for j in range(len(rowpixels)):
            if rowpixels[j]==255:
                edgelocationlist.append((i, j))
    return edgelocationlist

def plot_original_edge(original_image, edge_image):
    """ Create a subplot of the original image and the image of the edges. """
    plt.subplot(121),plt.imshow(original_image,cmap = 'gray')
    plt.title('Original Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(edge_image,cmap = 'gray')
    plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
    plt.show()

This is a link to a subplot that I have created with both images, the original one and the edge one: 7segments: original image and edges picture.

1 Answers

For each segment, you have a single contour. You can create a mask for one segment by drawing the corresponding contour (white, filled) on a black image. Finally, use cv2.mean, which accepts a mask parameter to get the mean RGB values within that mask, i.e. for that segment. If the color is the same for the whole segment, so the mean will be.

Related