python识别图形形状

代码

import cv2
import numpy as np

"""
查找图像轮廓,计算图像矩,根据公式计算轮廓周长和面积
面积:cv2.contourArea()|M['m00']
周长:cv2.arcLength()
    有两类边界矩形,直边界矩形,旋转边界矩形。
        直边界矩形(就是没有旋转的矩形),使用函数cv2.boundingRect()可以查找到,
        因为直边界矩形不考虑矩形旋转,所以直边界矩形的面积不是最小。

    旋转矩形,这个矩形的面积最小,因为他考虑了矩形的旋转。
        使用函数cv2.minAreaRect可以得到,函数返回一个Box2D结构,
        其中包含旋转矩形左上角坐标(x, y),矩形的宽高(w, h),以及旋转角度。
        但是绘制一个矩形需要四个角点,可以通过函数cv2.boxPoints()获得。
approxPolyDP(curve, epsilon, closed[, approxCurve]) -> approxCurve
第二个参数epsilon:指定原始轮廓到近似轮廓的最大距离,函数返回拟合的多边形边数。

"""


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


def getContours(img):
    # 查找轮廓,cv2.RETR_ExTERNAL=获取外部轮廓点, CHAIN_APPROX_NONE = 得到所有的像素点
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    # 循环轮廓,判断每一个形状
    for cnt in contours:
        # 获取轮廓面积
        area = cv2.contourArea(cnt)
        print(area)
        # 当面积大于500,代表有形状存在
        if area > 500:
            # 绘制所有的轮廓并显示出来
            cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
            # 计算所有轮廓的周长,便于做多边形拟合
            peri = cv2.arcLength(cnt, True)
            # 多边形拟合,获取每个形状的 边
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            print(len(approx))
            objCor = len(approx)
            # 获取每个形状的x,y,w,h
            x, y, w, h = cv2.boundingRect(approx)
            # 计算出边界后,即边数代表形状,如三角形边数=3
            if objCor == 3:
                objectType = "Tri"

            elif objCor == 4:
                # 判断是矩形还是正方形
                aspRatio = w / float(h)
                if aspRatio > 0.98 and aspRatio < 1.03:
                    objectType = "Square"
                else:
                    objectType = "Rectangle"
            # 大于4个边的就是圆形
            elif objCor > 4:
                objectType = "Circles"
            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)


path = 'Resources/shapes.png'
img = cv2.imread(path)
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.6, ([img, imgGray, imgBlur],
                             [imgCanny, imgContour, imgBlank]))

cv2.imshow("Stack", imgStack)

cv2.waitKey(0)

效果图

原图链接:
百度网盘链接: https://pan.baidu.com/s/1rTqz1hr0BY2u7Qmjw66VDQ 提取码:j34c

请添加图片描述

  • 11
    点赞
  • 142
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
识别图像中的形状和颜色,你可以使用PythonOpenCV来进行处理。下面是一个示例代码,演示了如何识别图像中的形状和颜色,并打印出它们: ```python import cv2 import numpy as np def get_shape(cnt): # 计算轮廓的周长 perimeter = cv2.arcLength(cnt, True) # 使用近似多边形方法将轮廓形状近似为多边形 approx = cv2.approxPolyDP(cnt, 0.04 * perimeter, True) # 根据多边形的边数来确定形状 if len(approx) == 3: shape = "Triangle" elif len(approx) == 4: shape = "Rectangle" elif len(approx) == 5: shape = "Pentagon" else: shape = "Circle" return shape def get_color(hsv_image, cnt): # 计算轮廓的掩模 mask = np.zeros(hsv_image.shape[:2], dtype=np.uint8) cv2.drawContours(mask, [cnt], -1, (255), thickness=cv2.FILLED) # 计算掩模中的平均颜色 mean_color = cv2.mean(hsv_image, mask=mask)[:3] # 根据颜色范围确定颜色 if mean_color[0] > 90 and mean_color[0] < 130: # 蓝色范围 color = "Blue" elif mean_color[0] > 0 and mean_color[0] < 30: # 红色范围 color = "Red" elif mean_color[0] > 30 and mean_color[0] < 90: # 绿色范围 color = "Green" else: color = "Other" return color # 读取图像 image = cv2.imread('image.jpg') # 将图像从BGR转换为HSV颜色空间 hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # 将图像转换为灰度图像 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 使用Canny边缘检测算法检测边缘 edges = cv2.Canny(gray_image, 50, 150) # 找到图像中的轮廓 contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 对每个轮廓进行处理 for cnt in contours: # 忽略过小的轮廓 if cv2.contourArea(cnt) < 100: continue # 获取形状和颜色 shape = get_shape(cnt) color = get_color(hsv_image, cnt) # 在原始图像上绘制形状和颜色信息 cv2.drawContours(image, [cnt], -1, (0, 255, 0), 2) cv2.putText(image, shape, (cnt[0][0][0], cnt[0][0][1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.putText(image, color, (cnt[0][0][0], cnt[0][0][1] + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示结果图像 cv2.imshow('Shape and Color Detection', image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在这个示例中,我们首先将图像从BGR颜色空间转换为HSV颜色空间,并将其转换为灰度图像。然后,我们使用Canny边缘检测算法找到图像中的边缘。接下来,我们找到图像中的轮廓,并对每个轮廓进行处理。通过计算轮廓的形状和颜色,我们可以确定物体的形状和颜色。最后,我们在原始图像上绘制出识别到的形状和颜色,并显示结果图像。 请注意,这只是一个基本的示例代码,你可以根据实际情况进行调整和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值