OpenCV第五发:图像像素的操作

#include <iostream>
#include <string>
#include <thread>
#include <math.h>
#include <Windows.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;

int main() {

	Mat src = imread("D:/opencv/Test06.jpg");

	//if (src.data == NULL) {
	//	printf("骚年:你应该继续查找你的文件路径是什么??或者你电脑是否需要换新的。");
	//	return -1;
	//}

	if (src.empty()) {//如果图像为空则返回 false
		printf("如果图像为空则返回 false");
		return -1;
	}
	//imshow("源图像", src);

	//转换为灰度空间,则图像的通道变为 1通道
	Mat CloneSrc = src.clone();
	//转换为单通道图像空间
	cvtColor(src, CloneSrc, CV_BGR2GRAY);
	cout << "转换为灰度空间之后,图像: " << CloneSrc.channels() << endl;

	//行对应高,列对应宽
	int H = CloneSrc.rows;
	int W = CloneSrc.rows;

	//每一份图像都是矩阵,因此只要是操作图像,则马上想到
	//用两个for循环
	for (int row = 0; row<H; row++) {
		for (int col = 0; col < W;col++) {
			//获取像素值
			int GrayPXI = CloneSrc.at<uchar>(row,col);
			//将每个像素值用255减去,则会重置每一个像素值。
			//如 5 = 255-250   250 = 255-5
			CloneSrc.at<uchar>(row, col) = 255 - GrayPXI;
		}	
	}
	//imshow("CloneSrc", CloneSrc);

	Mat ThreeChannl;
	ThreeChannl.create(src.size(),src.type());
	int H_three = ThreeChannl.rows;
	int W_three = ThreeChannl.cols;
	int tcchannls = ThreeChannl.channels();

	cout <<  "这个图像的通道数为: "  << tcchannls << endl;

	//行对应高,列对应宽
	for (int row = 0; row < H_three; row++)
	{
		for (int col = 0; col < W_three; col++) {
		
			if (tcchannls==1) {

				int GrayPXI = ThreeChannl.at<uchar>(row, col);
				//将每个像素值用255减去,则会重置每一个像素值。
				//如 5 = 255-250   250 = 255-5
				ThreeChannl.at<uchar>(row, col) = 255 - GrayPXI;
			
			}
			else if(tcchannls==3){
				/*
				在3通道RGB图像中,计算机储存结构为BGR,我们都知道,图像在计算机中实际上是以数组或者说矩阵形式储存
				在单通道图像中,图像的第一个像素值就是 [0]的所对应的值,
				例如 2*2 的 1 通道图像储存结构:
				{[Gray],[Gray]
				[Gray],[Gray]}

				但是在3通道图像中图像的 [0]储存结构是 [0]= {B,G,R}
				例如 2*2 的 3 通道图像储存结构:
				{[B,G,R],[B,G,R]
				 [B,G,R],[B,G,R]}
				 则这个 2*2 图像的3通道图像的列宽为 2*3=6 具体请查看相关的 《数字图像处理书籍》
				因此我们想要的到3通道第一个像素值B时候则应该 :
					int BB = src.at<Vec3b>(row, col)[0];
				对应的:
					int GG = src.at<Vec3b>(row, col)[1];
					int RR = src.at<Vec3b>(row, col)[2];				
				*/

				//读取像素值
				int BB = src.at<Vec3b>(row, col)[0];
				int GG = src.at<Vec3b>(row, col)[1];
				int RR = src.at<Vec3b>(row, col)[2];
				//重置像素值
				src.at<Vec3b>(row, col)[0]=1;
				src.at<Vec3b>(row, col)[1]=2;
				src.at<Vec3b>(row, col)[2]=3;
			}		
		}
	}

	//imshow("ThreeChannl", ThreeChannl);



	cout << endl;

	//加了这个图像就无法显示。
	//system("pause");
	waitKey(0);
	return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值