使用OpenCV-python实现手写数字识别

文章目录安装mahotas库智能提取阈值一、加载必要的库和一些基本函数二、定义hog算子来描述图片的特征三、根据已有数字类别标注的数据集来训练模型四、利用训练好的模型进行数字识别数据集下载和完整代码附录安装mahotas库智能提取阈值默认的conda环境是没有mahotas的,需要自己手动安装mahotas,注意不要使用pip install这种方式,可能会导致电脑死机!!!conda co...
摘要由CSDN通过智能技术生成

安装mahotas库智能提取阈值

默认的conda环境是没有mahotas的,需要自己手动安装mahotas,注意不要使用pip install这种方式,可能会导致电脑死机!!!

conda config --add channels conda-forge
conda install mahotas
# 查看一下是否已经安装好
conda list

一、加载必要的库和一些基本函数

import cv2
# from sklearn.externals import joblib
import joblib
import mahotas
import numpy as np
from sklearn.svm import LinearSVC
from skimage import feature

# 定义一个缩放函数
def resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]
    if width is None and height is None:
        return image
    # 高度模式
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    # 宽度模式
    else:
        r = width / float(w)
        dim = (width, int(h * r))
    resized = cv2.resize(image, dim, interpolation = inter)
    return resized

# 从excel加载数字,把特征和标注分开
def load_digits(datasetPath):
    data = np.genfromtxt(datasetPath, delimiter = ",", dtype = "uint8")
    target = data[:, 0]
    data = data[:, 1:].reshape(data.shape[0], 28, 28)
    return (data,target)

# 进行旋转变换
def deskew(image, width):
    (h, w) = image.shape[:2]
    moments = cv2.moments(image)
    skew = moments["mu11"] / moments["mu02"]
    M = np.float32([
        [1, skew, -0.5 * w * skew],
        [0, 1, 0]])
    image = cv2.warpAffine(image, M, (w, h),
        flags = cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
    image = resize(image, width = width)
    return image

# 把数字缩放到图片中心
def center_extent(image, size):
    (eW, eH) = size

    # 如果宽度》高度
    if image.shape[1] > image.shape[0]:
        image = resize(image, width = eW)
    else:
        image = resize(image, height = eH)

    extent = np.zeros((eH, eW), dtype = "uint8")
    offsetX = (eW - image.shape[1]) // 2
    offsetY = (eH - image.shape[0]) // 2
    extent[offsetY:offsetY + image.shape[0], offsetX:offsetX + image.shape[1]] = image

    # 计算图片的质量中心
    (cY, cX) = np.round(mahotas.center_of_mass(extent)).astype("int32")
    
  • 17
    点赞
  • 131
    收藏
    觉得还不错? 一键收藏
  • 25
    评论
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值