文章目录
安装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")