3.3 创建一个100*100的拥有三个通道的二维字节类型矩阵,将其元素全部置0。通过cvPtr2D函数将指针指向中间通道(绿色),以(20,5)和(40,20)为顶点间画一个绿色的长方形。
cvPtr2D的用法:
CvPtr2D能够根据参数中的行和列读取该位置的元素,但是该元素包含三个指针,分别控制蓝绿红。CvPtr2D指向的是元素的第一个指针,而该元素其他的颜色指针则为cvPtr2D(img,top,left)+1或+2。
1 /*ch4_lx3_3.cpp 2 添加功能:利用cvPtr2D函数画矩形 3 本程序是learning opencv这本书的课后习题练习 4 欢迎提出问题一起讨论*/ 5 #include "cv.h" 6 #include "highgui.h" 7 int main ( int argc, char** argv) 8 { 9 IplImage* firstimage = cvCreateImage(cvSize(100,100),IPL_DEPTH_8U,3);//创建一个图像对象 10 cvZero(firstimage);//把像素值全部置为0 11 int top=20,left=5,bottom=40,right=20; 12 //两条竖线 13 for(;top<=bottom;top++) 14 { 15 *(cvPtr2D(firstimage,top,left)+1)=255; 16 *(cvPtr2D(firstimage,top,right)+1)=255; 17 } 18 top=20; 19 //两条横线 20 for(;left<=right;left++) 21 { 22 *(cvPtr2D(firstimage,top,left)+1)=255; 23 *(cvPtr2D(firstimage,bottom,left)+1)=255; 24 } 25 cvNamedWindow("firstimage",1); 26 cvShowImage("firstimage",firstimage); 27 cvWaitKey(0); 28 cvReleaseImage(&firstimage); 29 cvDestroyWindow("firstimage"); 30 return 0; 31 }
程序运行结果如上图所示