OpenCv,对像素读取,修改,保存等操作

本文介绍了如何使用OpenCV库进行图像处理,包括读取图像、修改像素值、转换颜色空间及保存图像等基本操作。通过具体示例展示了不同方法访问和修改图像像素的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

imread

(1)功能:
读取一幅图像

(2)函数的声明格式:
Mat imread( const string& filename,int flags=1 );

(3)参数说明:
filename : 被读取的图像的名字
flags  说明读取图像的数据类型
如果flags>0 , 那么是把图像加载成3通道的彩色图像(注意:默认被加载成了一副彩色图像)
如果flags=0,那么把图像加载成灰度图(单通道的图像)
如果flags<0,那么如果图像本身是彩色图,就加载成彩色图,如果图像本身是灰度图就加载成灰度图。
如果图像加载失败,那么imread会返回一个空矩阵(Mat::data == NULL)

1,多种方式访问图像的像素

代码如下:

/*
*开发环境:Win7,VS2012
*OpenCv版本:2.4.9
*程序功能:多种方式操纵图像的每一个像素
*日期:2014/12/3
*原创:是
*作者:EbowTang
*Email:tangyibiao520@163.com
*/
// ConsoleAppOpenCvIterator.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;
/*
//最普通的操作方式at()遍历所有像素,并且对其进行操作
int _tmain(int argc, _TCHAR* argv[])
{
	Mat grayimg(256,480,CV_8UC1);
	Mat colorimg(256,480,CV_8UC3);
	
	for (int i=0;i<grayimg.rows;i++)
	{
		for (int j=0;j<grayimg.cols;j++)
		{
			grayimg.at<uchar>(i,j)=0;//对灰度图像素操作赋

值
		}
	}

	for (int i=0;i<colorimg.rows;i++)
	{
		for (int j=0;j<colorimg.cols;j++)
		{
			Vec3b pixel;
			pixel[0]=255;
			pixel[1]=155;
			pixel[2]=50;
			colorimg.at<Vec3b>(i,j)=pixel;
		}
	}

	cout<<grayimg.channels();
	imshow("grayimg",grayimg);
	imshow("colorimg",colorimg);
	waitKey(0);
	return 0;
}

*/

/*
//使用迭代器遍历所有像素,并且对其进行操作
int _tmain(int argc, _TCHAR* argv[])
{
	Mat grayimg(256,480,CV_8UC1);
	Mat colorimg(256,480,CV_8UC3);

	MatIterator_<uchar> grayst,grayend;
	grayst=grayimg.begin<uchar>();
	grayend=grayimg.end<uchar>();

	for (;grayst!=grayend;grayst++)
	{
		*grayst=rand()%255;
	}

	MatIterator_<Vec3b> Colorst,Colorend;
	Colorst=colorimg.begin<Vec3b>();
	Colorend=colorimg.end<Vec3b>();
	for (;Colorst!=Colorend;Colorst++)
	{
		(*Colorst)[0]=rand()%255;
		(*Colorst)[1]=rand()%255;
		(*Colorst)[2]=rand()%255;
	}

	imshow("grayimg",grayimg);
	imshow("colorimg",colorimg);
	waitKey(0);
}
*/
/*
//用指针遍历所有像素
int _tmain(int argc, _TCHAR* argv[])
{
	Mat grayimg(256,480,CV_8UC1);
	Mat colorimg(256,480,CV_8UC3);

	for (int i=0;i<grayimg.rows;i++)
	{
		uchar *p=grayimg.ptr<uchar>(i);//获取第i行的第一个像素
		for (int j=0;j<grayimg.cols;j++)
		{
			p[j]=(i+j)%255;
		}
	}
	//注意ptr是一个函数,其尖括号是在指明他的类型
	for (int i=0;i<colorimg.rows;i++)
	{
		Vec3b *p=colorimg.ptr<Vec3b>(i);
		for (int j=0;j<colorimg.cols;j++)
		{
			p[0]=255;
			p[1]=155;
			p[2]=50;
		}
	}

	cout<<grayimg.channels();
	imshow("grayimg",grayimg);
	imshow("colorimg",colorimg);
	waitKey(0);
	return 0;
}
*/


//读取一幅图像,并利用指针方式对像素进行更改
int _tmain(int argc, _TCHAR* argv[])
{
	Mat flower=imread("flower.jpg");
	Mat grayflower;
	cv::cvtColor(flower,grayflower,CV_BGR2GRAY);

	for (int i=grayflower.rows/2;i<grayflower.rows;i++)
	{
		uchar *p=grayflower.ptr<uchar>(i);//获取第i行的第一个

像素
		for (int j=0;j<grayflower.cols/2;j++)
		{
			p[j]=i*j%255;//对灰度图像素操作赋值
		}
	}


	for (int i=0;i<flower.rows/2;i++)
	{
		Vec3b *pixel=flower.ptr<Vec3b>(i);
		for (int j=flower.cols/2;j<flower.cols;j++)
		{
			pixel[j][0]=255;
			pixel[j][1]=255;
			pixel[j][2]=0;
		}
	}
	
	cout<<flower.channels()<<"   "<<grayflower.channels();
	imshow("灰度图的像素被操作",grayflower);
	imshow("彩色图的像素被操作",flower);
	waitKey(0);
}


2,保存图像操作

代码如下:

// ConsoleAppImwriteTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"  
#include <iostream>  
#include <vector>
using namespace cv; 
using namespace std;

void createAlphaMat(Mat &img)
{
	for (int i = 0; i < img.rows; ++i) {
		for (int j = 0; j < img.cols; ++j) {
			Vec3b& rgba = img.at<Vec3b>(i, j);
			//#define UCHAR_MAX     0xff      /* maximum unsigned char value */
			rgba[0] =0;//对通道1操作
			rgba[1] = saturate_cast<uchar>((float (img.cols - j)) / ((float)img.cols) * UCHAR_MAX);
			rgba[2] = saturate_cast<uchar>((float (img.rows - i)) / ((float)img.rows) * UCHAR_MAX);
			//rgba[3] = saturate_cast<uchar>((rgba[1] + rgba[2]));
		}
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	// Create mat with alpha channel
	Mat scr(480, 640, CV_8UC3);//8位深度,字符型,4通道,640x480尺寸
		createAlphaMat(scr);//创建图像
	vector<int> compression_params;
	compression_params.push_back(CV_IMWRITE_JPEG_QUALITY );//指定格式
	compression_params.push_back(50);//压缩等级,将影响图像质量
		imwrite("alpha.jpg", scr, compression_params);//写入图像
	cout<<"Saved jpg file with alpha data completely."<<endl;
	system("pause");
	return 0;
}


### 使用 OpenCV 读取彩色图像获取其基本信息 在 Python 中,可以利用 OpenCV 库来高效地读取彩色图像,进一步获取图像的尺寸、通道数和像素值。以下是具体方法: #### 1. 导入库 首先需要导入 `cv2` 和其他可能用到的库(如 NumPy),以便后续操作。 ```python import cv2 import numpy as np ``` #### 2. 读取彩色图像 使用 `cv2.imread()` 函数可以从文件路径加载一张图片。默认情况下,此函数将以 BGR 格式读取彩色图像[^1]。 ```python image_path = 'example.jpg' # 替换为实际图像路径 img = cv2.imread(image_path) if img is None: print("无法读取图像,请检查路径是否正确") else: print("成功读取图像") ``` #### 3. 获取图像尺寸 可以通过 `.shape` 属性获得图像的高度、宽度和通道数。返回的结果是一个元组 `(height, width, channels)`,其中第三个参数仅适用于多通道图像(如彩色图像)。如果图像是灰度图像,则只有两个维度 (高度和宽度)[^4]。 ```python dimensions = img.shape print(f"图像尺寸: 高度={dimensions[0]} 像素, 宽度={dimensions[1]} 像素") channels = dimensions[2] if len(dimensions) == 3 else 1 print(f"通道数量: {channels}") ``` #### 4. 访问单个像素值 要访问某个特定位置的像素值,可以直接通过数组索引来完成。例如,`img[y,x]` 返回位于第 y 行 x 列处的颜色向量;如果是三通道图像,则返回 `[B,G,R]` 形式的列表[^4]。 ```python pixel_value_bgr = img[100, 150] # 获取(100,150)坐标的BGR值 print(f"(100,150) 处的BGR值: {pixel_value_bgr}") blue_channel = pixel_value_bgr[0] green_channel = pixel_value_bgr[1] red_channel = pixel_value_bgr[2] print(f"B通道值: {blue_channel}, G通道值: {green_channel}, R通道值: {red_channel}") ``` 需要注意的是,在 OpenCV 中,默认采用 BGR 色彩空间而非标准 RGB 排序[^3]。 #### 5. 修改指定像素值 同样也可以修改某一点的像素值,只需重新赋值即可。 ```python img[100, 150] = [255, 0, 0] # 将(100,150)设置成纯蓝色(B=255,G=0,R=0) updated_pixel = img[100, 150] print(f"更新后的(100,150)像素值: {updated_pixel}") ``` 上述过程展示了如何基于 OpenCV 实现对彩色图像的基本操作,包括但不限于读取、查询大小信息以及调整个别像素点的内容。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值