OpenCV中的图像处理,特征提取,每一步的步骤,解释,都写在了代码旁边,容易解释。

import cv2
import numpy as np

# 预处理阶段
# 读取图片
pic_file = 'pic.png'
# 读取
image = cv2.imread(pic_file)
# 用于提取颜色特征的图片,必须是原图不能用灰度图
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 灰度图
img_bgr = cv2.imread(pic_file, cv2.IMREAD_GRAYSCALE)
# 原图,用于最后展示时使用
r_image = cv2.imread(pic_file)
# 原来图片缩小30%
per = 30
w = int(img_bgr.shape[1] * per / 100)
h = int(img_bgr.shape[0] * per / 100)
dim = (w, h)
# 三张图都要做
img = cv2.resize(img_bgr, dim, interpolation=cv2.INTER_AREA)
hsv_img = cv2.resize(hsv_img, dim, interpolation=cv2.INTER_AREA)
r_image = cv2.resize(r_image, dim, interpolation=cv2.INTER_AREA)
# cv2.imshow("input", img)
# 高斯滤波处理
img = cv2.GaussianBlur(img, (5, 5), 0)
# cv2.imshow('blurred', img)
img_copy = img.copy()
# 二值法
ret, binary = cv2.threshold(img_copy, 100, 255, cv2.THRESH_BINARY)
# cv2.imshow('binary',binary)
# 腐蚀与膨胀的形态学操作
kernel = np.ones((5, 5), np.uint8)
# 第三个参数是值操作次数
erosion = cv2.erode(binary, kernel, iterations=2)
# cv2.imshow('fushi',erosion)
binary = cv2.dilate(erosion, kernel, iterations=4)
# cv2.imshow('pengzhang',binary)
# 这里利用像素进行了,图像的面积求值,更加准确

# 轮廓面积
height = binary.shape[0]
width = binary.shape[1]
k = 0
for i in range(height):
    for j in range(width):
        if binary[i, j].all() > 0:
            k += 1
# k 就是图像的面积
# 这里继续进行轮廓检测
ref_, refCnts, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1)

# 外接矩形面积
area2 = cv2.contourArea(refCnts[0])

# 外接矩形周长
length = cv2.arcLength(refCnts[0], True)

# 求出外接矩形的顶点
x, y, w, h = cv2.boundingRect(refCnts[0])

# 区域占空⽐(轮廓区域⾯积除以最⼩外接矩形⾯积)
ee = k / area2

started = (x - 5, y - 10)
stopped = (x + w + 5, y + h + 5)
# 画出图像的最小外接矩形
img = cv2.rectangle(img, started, stopped, (255, 255, 255), 2)
# 根据最小外接矩形进行裁剪,得出目标的图片
cropped = img[started[1]: stopped[1], started[0]: stopped[0]]    # 图像处理需要灰度图
hsv_img = hsv_img[started[1]: stopped[1], started[0]: stopped[0]]  # 颜色图,hsv需要原图
r_image = r_image[started[1]: stopped[1], started[0]: stopped[0]]  # 结果需要呈现原图

# 给图像加上标签
text1 = 'height:' + str(h)
text2 = "width:" + str(w)
text3 = 'area:' + str(k)
text4 = 'ee:' + str(ee)
cv2.putText(r_image, text1, (10, 20), 3, 0.3, (255, 255, 255), 1, cv2.LINE_AA, 0)
cv2.putText(r_image, text2, (10, 40), 3, 0.3, (255, 255, 255), 1, cv2.LINE_AA, 0)
cv2.putText(r_image, text3, (10, 60), 3, 0.3, (255, 255, 255), 1, cv2.LINE_AA, 0)
cv2.putText(r_image, text4, (10, 80), 3, 0.3, (255, 255, 255), 1, cv2.LINE_AA, 0)
print(h)
print(w)
print(ee)
print(area2)
print(k)
cv2.imshow('color', hsv_img)
cv2.imshow('shape', r_image)
cv2.waitKey()

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐