轮廓中心颜色cv2 python

2024-05-13 03:43:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习使用cv2来识别图像中的基本图形。我使用contour标识形状,使用cv2.moments()函数确定轮廓中心。然而,当我试图获取中心像素的BGR值时,我遇到了一个异常,即索引越界异常。其他(非特殊图形)轮廓的颜色也不正确。根据我的说法,cv2.moment(<;>;)返回不是实际坐标的类对象。如何应对这种情况?我需要找到图像中每个轮廓的颜色。我的代码是:

import cv2
import numpy as np

raw_image = cv2.imread('test5.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
myMap = {}

for contour in contours:
    approx = cv2.approxPolyDP(contour,0.02*cv2.arcLength(contour,True),True)
    #area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)
        M = cv2.moments(contour)
        xx = int(M["m10"] / M["m00"])
        yy = int(M["m01"] / M["m00"])
        print(raw_image[xx][yy])
        #shape recognization code ahead

图像是: enter image description here 例外情况是:

^{pr2}$

当我打印的形状是(598,898,3)。 我该怎么做?在


Tags: 图像image图形rawcv2filtered轮廓contour