简体   繁体   English

使用 Python 检测图像上的区域及其颜色

[英]Detect areas and their color on an image with Python

I have an image of a 7 segment display.我有一个 7 段显示器的图像。 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.作为起点,我创建了一个程序,在其中使用 OpenCV 的 Canny 边缘检测来检测线段的边缘。我还获得了这些边缘的位置。

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 .这是我用两个图像(原始图像和边缘图像)创建的子图的链接: 7segments: original image and edges picture

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, ie for that segment.最后,使用 cv2.mean,它接受掩码参数以获取该掩码内的平均 RGB 值,即该段的 RGB 值。 If the color is the same for the whole segment, so the mean will be.如果整个段的颜色相同,则均值相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM