PYthon
1.PIL库:
from PIL import Image
import numpy as np
#读取图片
img=Image.open('imname') #读取图片 返回Image 对象
img.convert('L') #返回 灰度图像 Image对象。
img=np.array(img) #将 Image 对象转换成 array 数组,这样可以方便的使用array数组处理图像
img=Image.fromarray(im) #将 array 转换成 Image 对象
################################################
#图像的保存
img.save('new.jpg')
#ROI
box=(100,100,400,400)
region=img.crop(box) #这里是Image 对象,array对象直接数组操作就是了
Opencv
1.Mat 对象对矩阵元素的访问方式
Mat 存储结构:

- Mat 的每一行是连续的存储空间。
- Mat有多种构造函数,包括拷贝构造函数,以及重载了=运算符。常用的有
Mat(Sizesize, inttype)
Mat(introws, intcols, inttype, constScalar&s)
Mat(constMat&m, constRect&roi)
Mat(constMat&m, constRange&rowRange, constRange&colRange=Range::all())
如:
im=Mat(3,4,CV_8UC3) //创建 3 Rows 3 Columns 3 Channels 元素为一个字节uchar
im.create(4,8,CV_8UC1) //create()函数释放掉内存重新创建。
Mat 元素的访问:
- 使用 at()模板函数 返回特定位置元素的引用。(单通道值类型,通道的数组类型)。逻辑是按坐标访问。
unchar value=grayIm.at<uchar>(i,j); //单通道,读取(i,j)元素。
for(int r=0;r<grayIm.rows;r++)
for(int c=0;c<grayIn.cols;c++)
grayIm.at<uchar>=(r+c)%255;
///////////////////////////////////////////////////////////////////////////
Vec3b pixel;
for(int r=0;r<colorIm.rows;r++)
{
for(int c=0;c<grayIm.cols;c++)
{
pixel[0]=i%255; //Blue
pixel[1] = j%255; //Green
pixel[2] = 0; //Red
colorIm.at<Vec3b>(i,j) = pixel;
}// 3通道元素的访问
}
Vec3b 的定义为:
typedefVec<uchar, 3>cv::Vec3b
- 迭代器方式 MatIterator_ 类 在“Mat.hpp”中声明
MatIterator_<uchar> grayit, grayend;
for( grayit = grayIm.begin<uchar>(), grayend =grayIm.end<uchar>(); grayit != grayend; ++grayit)
{
*grayit = rand()%255;
}//单通道
/////////////////////////////////////////////////////////////////////////////
MatIterator_<Vec3b> colorit,colorend;
for( colorit = colorIm.begin<uchar>(), colorend =colorIm.end<uchar>(); colorit != colorend; ++colorit)
{
(*colorit)[0]=rand()%255;
(*colorit)[1]=rand()%255;
(*colorit)[2]=rand()%255;
}//多通道
- Mat 的 step属性。其中每个元素,依次表示包含的每个维度的大小字节数,如二维中,step[0] 表示 每一行的大小,step[1]表示一行中每一维的大小也就是元素的大小。dims属性表示维度
addr(Mi0,i1,…im-1) = M.data + M.step[0] * i0 + M.step[1] * i1 + … +M.step[m-1] * im-1 (其中 m = M.dims M的维度) - .ptr和[]操作符
Mat 类可以使用,.ptr<>函数得到某一行的指针然后可以使用[]操作符访问其中的元素
// using .ptr and []
void colorReduce0(cv::Mat &image, int div=64) {
int nr= image.rows; // number of rows
int nc= image.cols * image.channels(); // total number of elements per line
for (int j=0; j<nr; j++) {
uchar* data= image.ptr<uchar>(j); //元素是单字节
for (int i=0; i<nc; i++) {
data[i]= data[i]/div*div + div/2;
}
}
}
- ROI
Mat A=Mat::eye(10,10,CV_32S);
//提取A的 1~3列(含1,不含3)
Mat B=A(Range::all(),Range(1,3));
//提取B的5~9行(含5,不含9)
Mat C=B(Range(5,9),Range::all);
Size size; Point ofs;
C.locateRoI(size,ofs)//size(width=10,height=10) 父图像的大小,ofs(x=1,y=5)左上角,相对于父左上角的偏移。
// create a new 320x240 image
Mat img(Size(320,240),CV_8UC3);
// select a ROI
Mat roi(img, Rect(10,10,100,100));
// fill the ROI with (0,255,0) (which is green in RGB space);
// the original 320x240 image will be modified
roi = Scalar(0,255,0);
网友评论