OpenCV图像处理05-图像操作

2021-03-04 10:45:18 浏览数 (2)

05-图像操作

代码语言:javascript复制
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;

int main() {
	Mat src,gray_src;
	src = imread("D:\heroRcData\opencvProject\arrowImg\02\01.jpg");
	if (!src.data) {
		cout << "could not load image..." << endl;
		return -1;
	}
	namedWindow("input image", CV_WINDOW_AUTOSIZE);
	imshow("input image", src);
	//********************************************************
	//单通道
	cvtColor(src, gray_src, CV_BGR2GRAY);
	int gray_rows = gray_src.rows;
	int gray_cols = gray_src.cols;
	namedWindow("gray image", CV_WINDOW_AUTOSIZE);
	imshow("gray image", gray_src);

	for (int i = 0; i < gray_rows; i  ) {
		for (int j = 0; j < gray_cols; j  ) {
			int gray_value = gray_src.at<uchar>(i, j);	//当前点的像素值
			gray_src.at<uchar>(i, j) = 255 - gray_value; //取反
		}
	}
	namedWindow("grayNegation image", CV_WINDOW_AUTOSIZE);
	imshow("grayNegation image", gray_src);

	//********************************************************
	//多通道
	Mat dst = Mat(src.size(), src.type());
	int dst_rows = dst.rows;
	int dst_cols = dst.cols;
	int dst_channels = dst.channels();
	for (int i = 0; i < dst_rows; i  ) {
		for (int j = 0; j < dst_cols; j = j  ) {
			if (dst_channels == 1) {
				int dst_value = dst.at<uchar>(i, j);	//当前点的像素值
				dst.at<uchar>(i, j) = 255 - dst_value;
			}
			else if (dst_channels == 3) {
				int dstB_Value = src.at<Vec3b>(i, j)[0];//B通道当前点的像素值
				int dstG_Value = src.at<Vec3b>(i, j)[1];//G通道当前点的像素值
				int dstR_Value = src.at<Vec3b>(i, j)[2];//R通道当前点的像素值
				dst.at<Vec3b>(i, j)[0] = 255 - dstB_Value;//取反
				dst.at<Vec3b>(i, j)[1] = 255 - dstG_Value;//取反
				dst.at<Vec3b>(i, j)[2] = 255 - dstR_Value;//取反
			}
		}
	}
	namedWindow("srcNegation image", CV_WINDOW_AUTOSIZE);
	imshow("srcNegation image", dst);

	//********************************************************
	//上述操作效果可以用bitwise_not(src,dst)实现
	Mat dst1;
	bitwise_not(src, dst1);
	namedWindow("srcNegation1 image", CV_WINDOW_AUTOSIZE);
	imshow("srcNegation1 image", dst1);

	waitKey(0);
	return 0;
}

修改图像像素值

代码语言:javascript复制
//1.灰度图像
image.at<uchar>(y,x) = 128;

//2.BGR三通道图像
image.at<Vec3b>(y,x)[0] = 128;
image.at<Vec3b>(y,x)[1] = 128;
image.at<Vec3b>(y,x)[2] = 128;

//3.空白图像赋值
image = Scalar(0); //Scalar(参数1, 参数2...) 参数个数与通道数相同

//4.ROI选择
Rect r(10,10,100,100);
Mat smallImg = img(r);

Vec3b与Vec3F

  • Vec3b对应BGR三通道的uchar类型数据
  • Vec3F对应BGR三通道的float类型数据
  • 把CV_8UC1转化成CV_32F实现如下:src.convertTo(dst, CV_32F);

0 人点赞