上节MATLAB R2021a 图像处理之旅 — 3我们介绍了图像的预处理和后处理的一些方式。接下来我们继续在此基础上,看看如何从图像中分类识别出账单收据类的图片。
5 图像分类与批处理
首先,根据之前章节的内容,将对图像二值化相关的操作集合到一个函数中方便调用。
function [signal,Ibw,stripes] = processImage(img)
% This function processes an image using the algorithm
% developed in previous chapters.
gs = im2gray(img);
gs = imadjust(gs);
H = fspecial("average",3);
gssmooth = imfilter(gs,H,"replicate");
SE = strel("disk",8);
Ibg = imclose(gssmooth, SE);
Ibgsub = Ibg - gssmooth;
Ibw = ~imbinarize(Ibgsub);
SE = strel("rectangle",[3 25]);
stripes = imopen(Ibw, SE);
signal = sum(stripes,2);
end
接下来我们进行分类处理,
I = imread("IMG_008.jpg"); //读取图片
[S,BW,BWstripes] = processImage(I); //处理图片
montage({I,BW,BWstripes}); //显示图片
//使用islocalmin,调整minprominence大小,保证得到的极小值个数为9
//因为我们认为极小值个数为9作为一个图片是否为账单图片
//除了使用islocalmin,还可以在app中选择find local extreme应用来实现
minIndices = islocalmin(S, 'ProminenceWindow',25,'MinProminence',70);
nMin = nnz(minIndices); //统计计算的极小值个数
isReceipt = (nMin >= 9); //如果极小值个数大于等于9,则分类为账单图片
最后,我们将把多幅图片创建为datastore,然后再用已经调试好的分类程序进行处理。创建分类处理函数classifyImage.
function isReceipt = classifyImage(I)
% This function processes an image using the algorithm developed in
% previous chapters and classifies the image as receipt or non-receipt
% Processing
gs = im2gray(I);
gs = imadjust(gs);
H = fspecial("average",3);
gssmooth = imfilter(gs,H,"replicate");
SE = strel("disk",8);
Ibg = imclose(gssmooth, SE);
Ibgsub = Ibg - gssmooth;
Ibw = ~imbinarize(Ibgsub);
SE = strel("rectangle",[3 25]);
stripes = imopen(Ibw, SE);
signal = sum(stripes,2);
% Classification
minIndices = islocalmin(signal,"MinProminence",70,"ProminenceWindow",25);
nMin = nnz(minIndices);
isReceipt = (nMin >= 9);
end
创建datastore,并分类显示账单图片。
ds = imageDatastore("testimages"); //创建image datastore
dataFilenames = ds.Files; //保存文件名
nFiles = numel(dataFilenames); //统计文件个数
isReceipt = false(1,nFiles); //创建结果,记录每个图片是否为账单图片
//对每张图片进行分类处理
for k = 1:nFiles
I = readimage(ds,k);
isReceipt(k) = classifyImage(I);
end
receiptFiles = ds.Files(isReceipt); //记录被判断为账单图片的文件
montage(receiptFiles); //显示账单图片
title("Receipts");
|