使用Python检测图像上的区域及其颜色
我有一个7段显示器的图像。我想跟踪每个片段的颜色。作为起点,我创建了一个程序,在该程序中,我使用OpenCV的Canny边缘检测来检测线段的边缘。我还获得了这些边的位置 我的问题是,我不知道如何检测边缘内的区域并获得它们的颜色。在此,我发布我的程序代码:使用Python检测图像上的区域及其颜色,python,python-imaging-library,cv2,canny-operator,Python,Python Imaging Library,Cv2,Canny Operator,我有一个7段显示器的图像。我想跟踪每个片段的颜色。作为起点,我创建了一个程序,在该程序中,我使用OpenCV的Canny边缘检测来检测线段的边缘。我还获得了这些边的位置 我的问题是,我不知道如何检测边缘内的区域并获得它们的颜色。在此,我发布我的程序代码: import cv2 from PIL import Image import numpy as np from matplotlib import pyplot as plt def size(name): ""
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()
这是我用原始图像和边缘图像创建的子地块的链接:
.对于每个分段,都有一个轮廓。通过在黑色图像上绘制相应的轮廓(白色,填充),可以为一个线段创建遮罩。最后,使用cv2.mean,它接受掩码参数以获得该掩码内的平均RGB值,即该段的平均RGB值。如果整个片段的颜色相同,则平均值为。请查看
cv2.FindOntours
上的许多教程或其中一个教程。如果你有静态的黑色背景和如此清晰的显示,那么这种方法应该比找到边缘并手动填充它们更有效。谢谢你@HansHirse,但我已经找到了轮廓。我想知道的是这些轮廓内的颜色,实际上是每个部分的颜色。对于每个部分,你有一个单独的轮廓。通过在黑色图像上绘制相应的轮廓(白色,填充),可以为一个线段创建遮罩。最后,使用cv2.mean
,它接受掩码参数以获得该掩码内的平均RGB值,即该段的平均RGB值。如果整个片段的颜色相同,那么平均值是。好的,谢谢。我将把它作为一个答案发布。