【发布时间】:2019-01-07 21:24:37
【问题描述】:
我正在处理需要找到轮廓内区域颜色的要求。我们在 Python 中使用 OpenCv,这是我在 Python 中的代码:
import imutils
import cv2
import numpy as np
path = "multiple_grains_1.jpeg"
img = cv2.imread(path)
resized = imutils.resize(img, width=900)
ratio = img.shape[0] / float(resized.shape[0])
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
(ret, thresh) = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
edge = cv2.Canny(thresh, 100, 200)
( _,cnts, _) = cv2.findContours(edge.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
area = cv2.contourArea(c)
if area > 1:
cv2.drawContours(resized,[box],0,(0,0,255),2)
cv2.drawContours(resized, [c], -1, (0, 255, 0), 2)
#print("area : "+str(area))
#print('\nContours: ' + str(c[0]))
#img[c[0]]
pixelpoints = np.transpose(np.nonzero(c))
#print('\pixelpoints: ' + str(pixelpoints))
# accessed the center of the contour using the followi
M = cv2.moments(c)
if M["m00"] != 0:
cX = int((M["m10"] / M["m00"]) * ratio)
cY = int((M["m01"] / M["m00"]) * ratio)
#print (cX,cY)
cord = img[int(cX)+3,int(cY)+3]
print(cord)
cv2.imshow("Output", resized)
cv2.waitKey(0)
exit()
当我检查轮廓的质心颜色时,我无法获取正确的颜色。有人知道如何使用 OpenCv 和 python 获取轮廓内的颜色吗?
【问题讨论】:
-
使用KMeans获取轮廓指定区域的主色。
-
我可以建议你采取每个轮廓的边界框来获取对象的四个角。然后我认为内部像素颜色提取很容易。
-
@zindarod 你能写一个答案吗?这样我就可以知道如何进行了。
-
@Seenu69 This article 解释得很好。
-
你也可以调查一下 cv2.connectedComponents 和 cv2.connectedComponentsWithStats 也许这个programcreek.com/python/example/89340/…可以帮到你
标签: python opencv image-processing opencv-contour