Size dsize = new Size(img.width() * scale, img.height() * scale);Mat img2 = new Mat();Imgproc.resize(img, img2, dsize);
scale为缩放的大小
resize函数参数1为原图,参数2为缩放之后的图
2、图片读写
Mat img = Highgui.imread(bitmappath);Highgui.imwrite("/mnt/sdcard/www.png", thumb2);
3、bitmap转为Mat
Mat bgImg = Utils.bitmapToMat(bm); Imgproc.cvtColor(bgImg, bgImg, Imgproc.COLOR_RGB2BGR, 3);
第二行代码是颜色值转换,因为从实验来看,bitmap转为mat之后,红蓝值可能会发生颠倒,因而用此方法再将颜色值转回来
4、Mat旋转
5、Mat截取Mat mat_bmp = img2; double radians = Math.toRadians(90); double sin = Math.abs(Math.sin(radians)); double cos = Math.abs(Math.cos(radians)); int width = mat_bmp.width(); int height = mat_bmp.height(); int newWidth = (int) (width * cos + height * sin); int newHeight = (int) (width * sin + height * cos); // 能把原图像和旋转后图像同时放入的外框 int frameWidth = Math.max(width, newWidth); int frameHeight = Math.max(height, newHeight); Size frameSize = new Size(frameWidth, frameHeight); Mat mat_frame = new Mat(frameSize, mat_bmp.type()); // 将原图像copy进外框 int offsetX = (frameWidth - width) / 2; int offsetY = (frameHeight - height) / 2; Mat mat_frame_submat = mat_frame.submat(offsetY, offsetY + height, offsetX, offsetX + width); mat_bmp.copyTo(mat_frame_submat); // 旋转外框 Point center = new Point(frameWidth / 2, frameHeight / 2); Mat mat_rot = Imgproc.getRotationMatrix2D(center, 90, 1.0); Mat mat_res = new Mat(); // result Imgproc.warpAffine(mat_frame, mat_res, mat_rot, frameSize, Imgproc.INTER_LINEAR, Imgproc.BORDER_CONSTANT, Scalar.all(0)); // 从旋转后的外框获取新图像 offsetX = (frameWidth - newWidth) / 2; offsetY = (frameHeight - newHeight) / 2; Mat mat_res_submat = mat_res.submat(offsetY, offsetY + newHeight, offsetX, offsetX + newWidth);
Mat imageVROI = mat_res_submat.submat(roi);
roi为Rect,例如:Rect roi = new Rect(0, 0, width, height);
6、图片合成(添加水印)
假如frontImg为要添加的图,bgImg为背景图
Mat imageROI = bgImg.submat(new Rect(a, b, c, d));frontImg.copyTo(ImageROI,frontImg);
Rect第一、二个参数分别为前面的要添加到背景图的横纵坐标,三、四参数为宽高。
7、遍历像素
byte sdata[] = { 0, 0, 0 };byte ndata[] = { 0, 0, 0 };for (int i = 0; i < img.rows(); i++){for (int j = 0; j < img.cols(); j++){if (img.channels() == 3){img.get(i, j, sdata);if ((sdata[0] == (byte) 255) && (sdata[1] == (byte) 20) && (sdata[2] == (byte) 255))img.put(i, j, ndata);}}}
上面代码实现的操作为遍历所有像素,并将颜色值为255,20,255的像素点替换为颜色值为0,0,0