我正在学习使用cv2来识别图像中的基本数字。我使用轮廓来识别形状,使用cv2.moments()函数来确定轮廓的中心。然而,当我试图获得中心像素的#BGR值时,我得到一个异常作为索引超出范围的异常。其他(非特殊数字)轮廓的颜色也不正确。根据我的说法,cv2.moment(< _>)返回 Point 类对象,这不是实际的坐标。如何应对这种情况?我需要找到图像中存在的每个轮廓的颜色。这是我的代码:
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
File "colourTmp.py", line 29, in <module>
print(raw_image[xx][yy])
IndexError: index 788 is out of bounds for axis 0 with size 598
当我打印 raw_img 的形状时,它来到了(598,898,3)。 我该怎么办?