首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用python在OpenCv中查找轮廓的颜色

如何用python在OpenCv中查找轮廓的颜色
EN

Stack Overflow用户
提问于 2018-07-31 21:05:10
回答 1查看 3.5K关注 0票数 3

我正在处理一个要求,我需要找到区域内轮廓的颜色。我们在Python中使用OpenCv,下面是我在Python中的代码:

代码语言:javascript
复制
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来获取轮廓中的颜色吗?

EN

回答 1

Stack Overflow用户

发布于 2018-08-20 04:01:45

我简化了你的代码,并且能够在不使用矩的情况下获得质心的颜色。

代码语言:javascript
复制
import imutils
import cv2
import numpy as np
import matplotlib.pyplot as plt


img = cv2.imread("multiplegrains.png")
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)
_, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# if you want cv2.contourArea >1, you can just comment line bellow
cnts = np.array(cnts)[[cv2.contourArea(c)>10 for c in cnts]]
grains = [np.int0(cv2.boxPoints(cv2.minAreaRect(c))) for c in cnts]
centroids =[(grain[2][1]-(grain[2][1]-grain[0][1])//2, grain[2][0]-(grain[2][0]-grain[0][0])//2) for grain in grains]

colors = [resized[centroid] for centroid in centroids]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51614092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档