标签:
一、Accessingpixel values访问像素值。(用类自带的方法:方便,但效率不高)
1. cv::Mat has the a templatemethod at(int y, int x)
用法image.at<cv::Vec3b>(j,i)[channel]= value;
注意事项:the programmer needs to specify the return type that is expected(需认为指定返回值类型),一般使用type cv::Vec3b. It is a vector of 3 unsigned chars.
2. 使用cv::Mat_ 类,它是cv::Mat 的一个模板子类,有相同的数据结构,但是增加了一些新的方法。所以这两个类的指针或引用可以直接相互转换。
用法:使用cv::Mat_ 类中新增加的方法()操作符,可以直接访问图像像素。
cv::Mat_<uchar>im2= image; // im2 refers to image
im2(50,100)= 0; // access to row 50 and column 100
注意事项:要将image的引用或者指针赋值给cv::Mat_类变量才可以使用()操作符。
二、Scanning animage with pointers(使用指针扫描图像:效率高)
彩色图像三个通道,opencv中默认顺序是BGR, blue 总是第一个通道。(有些处理器对于长宽是4 or 8 的倍数的图像更加高效,所以有些图像会有 额外的padded填补的像素,为了提高效率Obviously,these extra pixels are not displayed or saved, their exact values are ignored)
ptr 方法
1. 基本信息:
a. cols : gives you the image width (thatis the number of columns)
b. rows: gives you the image height
c. step data: gives you the effective widthin number of bytes
d. method elemSize: returns the size of apixel element (for example, for a 3-channel short integer matrix (CV_16SC3),elemSize will return 6)
e. method nchannels: returns the number ofchannels in the image
f. method total: returns the total numberof pixels (that is matrix entries) in the matrix
3. 使用方法:
a. The number of pixel values per rows is then given by:
intnc= image.cols * image.channels();
b. ptr method. It is a template method thatreturns the address of row number j :
uchar*data= image.ptr<uchar>(j);
c. 用指针操作的一个例子(color reduce)
*data++=*data/div*div + div2;
或者
data[i]= data[i]/div*div+ div/2;
或者
data[i]=data[i] – data[i]%div + div/2; (有点慢,要访问每个像素两次)
或者
按位操作:if we restrict the reductionfactor to a power of 2, that is, div=pow(2,n) , then masking the fist n bits ofthe pixel value would give us the nearest lower multiple of div. This maskwould be computed by a simple bit shift:
//mask used to round the pixel value
uchar mask=0xFF<<n; // e.g. for div=16, mask= 0xF0
The color reduction would be given by:
data[i]= (data[i]&mask) +div/2;
4. 注意事项:
三、给出高效 扫描处理(连续)图像的标准例子
void colorReduce(cv::Mat &image, intdiv=64)
{
int nl= image.rows; // number of lines
int nc= image.cols * image.channels();
if (image.isContinuous())
{
// then no padded pixels
nc= nc*nl;
nl= 1; // it is now a 1Darray
}
// this loop isexecuted only once
// in case ofcontinuous images
for (int j=0;j<nl; j++)
{
uchar* data=image.ptr<uchar>(j);
for (int i=0; i<nc; i++)
{
// process each pixel---------------------
data[i]= data[i]/div*div +div/2;
// end of pixel processing----------------
} //end of line
}
}
标签:
原文地址:http://blog.csdn.net/hyqsong/article/details/46051495