使用OpenCV读、操作、写图像并与bash合作对某个文件夹下全部图像进行相似处理...

我门要对某个文件夹下全部图像文件进行统一处理,假设图像的数量过多。那么手动地一张张处理就会显得有些麻烦。本文使用OpenCV和bash来完毕我们指定的任务。


任务

将文件夹A下的全部统一格式的jpg图像变成统一尺寸的图像,输出到文件夹B中。A文件夹下图像的宽度和高度须要去掉最后一列、最后一行,而且使得输出图像的高度小于宽度。


技术

OpenCV读取图像;訪问图像中的元素。OpenCV写图像到磁盘。

BASH扫描每一个输入图像;确定输出图像名称。


OpenCV对图像进行处理

源码例如以下:

#include <cassert>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "cv.hpp"
#include "opencv2/opencv.hpp"
//#include "opencv2/core.hpp"
#include "opencv2/highgui/highgui_c.h"

using namespace std;
using namespace cv;

int main(int argc, char **argv)
{
	if (3 != argc){
		cerr << "input error\n";
		cerr << "Usage : " << argv[0] << " <input image> <output directory>" << endl;
		return -1;
	}
	// reading the input image
	Mat oim = imread(argv[1]);
	if (oim.empty())
		return -1;

	const int rows = oim.rows;
	const int cols = oim.cols;
	Mat fim(rows-1, cols-1, CV_8UC3);

	for (int r = 0; r < (rows-1); r++){
	for (int c = 0; c < (cols-1); c++){
		fim.at<Vec3b>(r,c) = oim.at<Vec3b>(r,c);
	}}
	// rotate 90'
	Mat lim;
	if (rows > cols){
		lim.create(cols-1, rows-1, CV_8UC3);
		for (int r = 0; r < (cols-1); r++){
		for (int c = 0; c < (rows-1); c++){
			lim.at<Vec3b>(r,c) = fim.at<Vec3b>(c,cols-2-r);
		}}
	}
	else{
		lim = fim;
	}
	// saving
	string filename(argv[1]);
	int dirpos = filename.find_last_of('/');
	if (string::npos == dirpos){
		dirpos = 0;
	}
	else{
		dirpos += 1;
	}
	string wfn = &filename[dirpos];
	string outdir = string(argv[2]);
	string outfile = outdir+string("/")+wfn;

	vector<int> compression_params;
	compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
	compression_params.push_back(100);
	imwrite(outfile, lim, compression_params);
	if(lim.cols != 480 || lim.rows != 320)
		cerr << "size error" << endl;

	return 0;
}


程序分三大步骤完毕:读如程序选项中的输入图像;对输入图像去除最后一行和最后一列。推断高度和宽度的要求(是否进行反转90度)。将图像写入磁盘。

写入磁盘时。使用了jpeg压缩方式,压缩的參数设置为100,表示无失真压缩。

输入图像的名称和输出图像的名称使用同一个。


bash处理

用bash对某个文件夹下的全部图像都处理一次,而且输出到指定的文件夹。源码例如以下:

SPS="input/"

DFS=`ls -A ${SPS}*.jpg`

JPGDIR="../output/jpg"

mkdir -p ${JPGDIR} 

for fn in $DFS
do
  echo $fn
  ./rmRowACols.exe $fn $JPGDIR 
done


总结

BASH+C/C++ 合作来完毕一个完整的任务,各取所长,兼顾性能和开发难度,眼下被我觉得是比較简单的方式。

这样作另一个优点:C\C++语言能够做很多其它细节,别调用别人的程序要任意一点。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值