import cv2
import numpy as np
#用来进行图像的堆栈代码,可以复制使用
def stackImages(scale,imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range ( 0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
                if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank]*rows
        hor_con = [imageBlank]*rows
        for x in range(0, rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)
    else:
        for x in range(0, rows):
            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor= np.hstack(imgArray)
        ver = hor
    return ver


#轮廓contour
# 特征feature
# 面积area
# 弧长perimeter
# 图像矩image moment
def getContours(img):
    #img是二值图像
    contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)#返回值一个是轮廓本身,还有一个是每条轮廓对应的属性。

    for cnt in contours:
        area = cv2.contourArea(cnt)#求得轮廓的面积
        #输出轮廓的面积
        print('轮廓的面积',area)

        if area>500:
            cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
            #计算轮廓周长
            peri = cv2.arcLength(cnt,True)#这个函数的第二参数可以用来指定对象的形状是闭合(True),还是打开的(一条曲线)

            print('轮廓的周长',peri)

            #轮廓近似
            approx = cv2.approxPolyDP(cnt,0.02*peri,True)#输出的是多边形的顶点坐标

            print(approx)
            #输出坐标的个数
            print(len(approx))
            objCor = len(approx)
            #获得图像的最小矩形信息
            x, y, w, h = cv2.boundingRect(approx)
            #判断输出坐标的个数
            if objCor ==3: objectType ="sjx"
            elif objCor == 4:
                aspRatio = w/float(h)

                if aspRatio >0.98 and aspRatio <1.02: objectType= "zfx"

                else:objectType="jx "

            elif objCor>4: objectType= "y"

            else:objectType="None"
            #画出三角形并和文本
            cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)
            cv2.putText(imgContour,objectType,(x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,0.7,(0,0,0),2)


img = cv2.imread('shapes.png')
imgContour = img.copy()
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(7,7),1)
imgCanny = cv2.Canny(imgBlur,50,50)
getContours(imgCanny)
imgBlank = np.zeros_like(img)
imgStack = stackImages(0.8,([img,imgGray,imgBlur],
                            [imgCanny,imgContour,imgBlank]))
cv2.imshow("Stack", imgStack)
cv2.waitKey(0)

通过对opencv基础知识的学习,我们利用简单的函数进行对物体形状及轮廓进行识别和显示,基本操作是:

对图片进行一系列操作(灰度化,模糊化,二值化,提取边缘轮廓),并进行轮廓的寻找和绘制,通过轮廓可以获得角点的坐标并进行形状的判断,最后输出相应的形状类型。

原图片如下:

 

 仅供学习参考,如有不足,敬请指正!

GitHub 加速计划 / opencv31 / opencv
238
21
下载
OpenCV: 开源计算机视觉库
最近提交(Master分支:4 个月前 )
1f47f5ba imgproc: replace assertion in cornerSubPix with descriptive error #28404 Replace CV_Assert with explicit bounds check for initial corners in cornerSubPix. This provides a descriptive runtime error instead of abrupt termination, improving error handling for Python and C++ users. No algorithmic or behavioral change for valid inputs. Fixes #25139 (Related to #7276). ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [ ] The feature is well documented and sample code can be built with the project CMake 7 小时前
fba658b9 Improve precision of RotatedRect::points 1 天前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐