【实例简介】对于图像的边缘处理、腐蚀、面积等基础处理,对该图像进行二值化处理,利用二值化结果,计算面积及质心,计算出其主轴方向,Hough拟合以下图像中直线边缘,显示结果,并将斑马线区域部分标记出来。
【实例截图】
【核心代码】
# -*- coding: utf-8 -*-
# @Descript:
# (1)对该图像进行二值化处理
# (2)利用二值化结果,计算面积及质心
# (3)计算出其主轴方向
import cv2 as cv
import matplotlib.pyplot as plt
import math
img = cv.imread("3-1.jpg")
#二值化 灰度图
ret, thresh = cv.threshold(cv.cvtColor(img,cv.COLOR_BGR2GRAY), 127, 255, 0)
#轮廓提取 得到轮廓信息
# findContours 传入参数 输入图像 轮廓检索模式 轮廓近似方法
# contours,hierarchy= cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
contours,hierarchy= cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
#取第一条轮廓
cnt = contours[0]
#print(contours)
area = cv.contourArea(cnt)
M = cv.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
#计算面积和质心
a = int(M['m20']/M['m00'])
b = int(M['m11']/M['m00'])
c = int(M['m02']/M['m00'])
square = math.sqrt(4*b*b (a-c)*(a-c))
theta = math.atan2(2*b,a-c square) *180 / math.pi
# print(M)
print("面积:" str(area))
print("质心:" str(cx) "," str(cy))
print("主轴方向:" str(theta))