微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在opencv-python中检测星形

我需要检测形状并计算图像中每个形状的出现.我最初检测到轮廓并对它们进行近似,并计算每个轮廓中的顶点.我的代码如下所示:

import cv2
import numpy as np 
import collections
import sys

img = cv2.imread(str(sys.argv[1]),0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh,1,2)


no_of_vertices = []

i = 0
mask = np.zeros(img.shape,np.uint8)
for contour in contours:

 cnt = contour
 area = cv2.contourArea(cnt)
 if area>150:
    epsilon = 0.02*cv2.arcLength(cnt,True)
    approx = cv2.approxpolyDP(cnt,epsilon,True)
    no_of_vertices.append(len(approx))



counter = collections.Counter(no_of_vertices)




 a,b = counter.keys(),counter.values()

 i=0
 while i

我的代码不能用于检测此图像中的星星:

Image with stars and other basic shapes

我应该在代码中做出哪些更改?

最佳答案
我有用的是比较形状周边区域的平方根.一颗恒星约为0.145(/ – .0015,因为有些边缘没有完美出现).六边形为0.255,三角形为.21,正方形为.247,五边形为.250.

圆度也起作用(三角形在0.26到.27之间),并且它的区别相似(六边形为.83,三角形为.55-.56,正方形为.77,五边形为.78) )

下面是它的C代码(我的PC上没有python,但想法是一样的):

#include "stdafx.h"
#include xcore.h>
#include xcore.h>
#include norMAL| CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED);

   threshold(imgrey,100,0);

   findContours(imgrey,imContours,hierarchy,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,Point(0,0) );

    for (int i=0; i < imContours.size(); i++) {
         Scalar color = Scalar( rngee.uniform(0,255),rngee.uniform(0,255) );
         cout << "sqrt(Area)/arcLength = " << sqrt(contourArea(imContours[i]))/arcLength(imContours[i],true ) << endl;
         if(sqrt(contourArea(imContours[i]))/arcLength(imContours[i],true ) < divMaxSize && sqrt(contourArea(imContours[i]))/arcLength( imContours[i],true ) > divMinSize) 
         {
             drawContours(im,i,color,2,8,Point() ); 
             cout << "I'm a star!" << endl;
         }
        imshow("Image",im);
        waitKey(0);
    }
    imshow("Image",im);
    waitKey(0);

}

两种方式 – 使用圆形或我的sqrt(区域)/ arclength方法 – 导致:

原文地址:https://www.jb51.cc/python/438455.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐