【问题标题】:Detect areas and their color on an image with Python使用 Python 检测图像上的区域及其颜色
【发布时间】:2021-04-19 07:08:45
【问题描述】:

我有一个 7 段显示器的图像。我想跟踪每个段的颜色。作为起点,我创建了一个程序,在该程序中我使用 OpenCV 的 Canny 边缘检测来检测片段的边缘。我也得到了这些边的位置。

我的问题是我不知道如何检测边缘内的那些区域并获得它们的颜色。在这里,我贴出我的程序代码:

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()

这是我用两张图片创建的子图的链接,原始图片和边缘图片: 7segments: original image and edges picture.

【问题讨论】:

  • 查看contours and how to find themcv2.findContours 上的众多教程之一。如果你有静态的黑色背景和如此清晰的显示,那么这种方法应该比找到边缘并手动填充它们更好。
  • 谢谢@HansHirse,但我已经找到了轮廓。我想知道的是位于这些轮廓内的颜色,实际上是每个段的颜色。
  • 对于每个段,您都有一个轮廓。您可以通过在黑色图像上绘制相应的轮廓(白色、填充)来为一个片段创建蒙版。最后,使用cv2.mean,它接受一个掩码参数来获取该掩码内的平均 RGB 值,即该段。如果整个段的颜色相同,那么平均值就是。
  • 好的,谢谢。我会把它作为答案发布。

标签: python python-imaging-library cv2 canny-operator


【解决方案1】:

对于每个段,您都有一个轮廓。您可以通过在黑色图像上绘制相应的轮廓(白色,填充)来为一个片段创建蒙版。最后,使用 cv2.mean,它接受一个掩码参数来获取该掩码内的平均 RGB 值,即该段。如果整个段的颜色相同,那么平均值就是。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 2018-01-19
    • 2015-11-09
    • 2011-01-17
    • 2020-05-25
    • 2021-07-31
    • 2011-12-05
    • 1970-01-01
    相关资源
    最近更新 更多