最近在学习OpenCv相关知识,在Python中利用cv等库可以轻松实现相关操作。

Canny边缘检测

在Python的cv2库中,进行Canny边缘检测方法极其简单,只需要利用

import cv2
cv2.Canny()

为了更好的边缘检测效果,在进行Canny边缘检测之前我们要对图片或视频进行一定的降噪处理,去除图片中 的噪点,我们来看一下去除噪点前和去除噪点后进行边缘检测的差距。
下面是原图、直接进行Canny边缘检测、降噪后进行Canny检测:
原图、直接进行Canny边缘检测、降噪后进行Canny检测
两种基本的形态学变换是侵蚀和膨胀,他们的变种也有张开和闭合

下面直接上代码使用:
侵蚀:

import numpy as np
import cv2
kernel = np.ones((3,3),dtype=np.int8)
ersion1 = cv2.erode(gray.copy(),kernel,iterations=1)

膨胀

import numpy as np
import cv2
kernel = np.ones((3,3),dtype=np.int8)
dilation1 = cv2.dilate(gray.copy(),kernel,iterations=1)

张开

import numpy as np
import cv2
kernel = np.ones((10,10),dtype=np.int8)
opening1 = cv2.morphologyEx(gray.copy(),cv2.MORPH_OPEN,kernel)

闭合

import numpy as np
import cv2
kernel = np.ones((20,20),dtype=np.int8)
closing1 = cv2.morphologyEx(gray.copy(),cv2.MORPH_CLOSE,kernel)

下面为演示使用代码:

import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./test_imgs/shufa.jpg')
img_no_process = img.copy()
img_process = img.copy()
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)


# 二值化处理
r,black_img = cv2.threshold(img_gray,100,255,cv2.THRESH_BINARY_INV)
# 侵蚀
erodition = cv2.erode(black_img,np.ones((3,3),dtype=np.int8),iterations=1)
# 膨胀
dilation = cv2.dilate(erodition,np.ones((5,5),dtype=np.int8),iterations=1)
# 闭合
closing = cv2.morphologyEx(dilation,cv2.MORPH_CLOSE,np.ones((30,30),dtype=np.int8))
canny =  cv2.Canny(img_gray,30,200)
canny_process = cv2.Canny(closing,30,200)

# 找轮廓
coutours1,h = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
coutours2,h = cv2.findContours(canny_process,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for c in coutours1:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(img_no_process,(x,y),(x+w,y+w),(255,0,255),3)
for c in coutours2:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(img_process,(x,y),(x+w,y+w),(255,0,255),3)
fig,(ax2,ax3,ax4) = plt.subplots(1,3,figsize=(20,8),sharex=True,sharey=True)

ax2.axis('off')
ax2.imshow(img_gray,cmap='gray')


ax3.axis('off')
ax3.imshow(img_no_process,cmap='gray')

ax4.axis('off')
ax4.imshow(img_process,cmap='gray')

HOG特征提取并使用支持向量机(SVM)进行书法分类训练

首先安装scikit-learn、scikit-image,SVM需从scikit-learn模块中导出使用,HOG从scikit-image模块导出使用,

pip install  scikit-learn
pip install scikit-image

目录层次

# HOG方法参数
# image:输入图像
# orientations:把180度分成几份,bin的数量
# pixels_per_cell :元组形式,一个Cell内的像素大小
# cells_per_block: 元组形式,一个Block内的Cell大小
# visualize: 是否需要可视化,如果True,hog会返回numpy图像
def imageReader(filename):
    # 读取
    img = readImg(filename)
    # 缩放
    img = cv2.resize(img,(100,100))
    # 灰度
    img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    return img
# 批量读取文件数据 提取HOG特征
import os
import glob
import random
from skimage.feature import hog
from skimage import data,exposure
list_1 = glob.glob('./images/行书/*/*')
print(len(list_1))
featurn_list = []
label_list  = []
style__list = ['篆书','隶书','草书','行书','楷书']
for style in style__list:
    print('开始遍历:{style}'.format(style=style))
    file_list = glob.glob('./images/' + style + '/*/*')
    # 随机打乱文件顺序
    random.shuffle(file_list)
    selected_files = file_list[:1000]
    for file_item in selected_files:
        # 遍历文件名列表
        # 打开图片、缩放、灰度
        img_gray = imageReader(file_item)
        # 特征提取
        fd = hog(img_gray,orientations=4,pixels_per_cell=(6,6),cells_per_block=(2,2))
        # 提取图片类别标签
        label = style__list.index(style)

        # 放入特征和标签列表
        featurn_list.append(fd)
        label_list.append(label)

# 导入SVM模型
from sklearn import svm
# 将样本分为训练和测试样本
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(featurn_list,label_list,test_size=0.25,random_state=42)
# rbf、linear、poly
cls = svm.SVC(kernel='linear') 
cls.fit(x_train,y_train)
predict_labels = cls.predict(x_test)
from sklearn.metrics import accuracy_score
print(accuracy_score(y_test,predict_labels))

# 保存模型
from joblib import dump,load
dump(cls,'./models/poly.joblib')
最后修改:2023 年 01 月 24 日
如果觉得我的文章对你有用,请随意赞赏