歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 利用OpenCV生成關於某點的顏色徑向均勻漸變圖像

利用OpenCV生成關於某點的顏色徑向均勻漸變圖像

日期:2017/3/1 10:10:36   编辑:Linux編程

利用OpenCV生成關於某點的顏色徑向均勻漸變圖像:

  1. #include "cv.h"
  2. #include "highgui.h"
  3. #include <math.h>
  4. #pragma comment(lib,"highgui.lib")
  5. #pragma comment(lib,"cxcore.lib")
  6. #pragma comment(lib,"cv.lib")
  7. int main( int argc, char** argv )
  8. {
  9. IplImage* image = cvCreateImage(cvSize(800,600),IPL_DEPTH_8U,3);
  10. if(!image)
  11. {
  12. return -1;
  13. }
  14. CvScalar a=CV_RGB(0,255,0);
  15. CvScalar b=CV_RGB(0,0,0);
  16. cvSet(image,a);
  17. CvPoint origin=cvPoint(800,600);
  18. CvPoint center=cvPoint(image->width/2,image->height/2);
  19. double distance;
  20. if(origin.x<=center.x && origin.y<=center.y)
  21. {
  22. distance=sqrt((image->width-1-origin.x)*(image->width-1-origin.x)+
  23. (image->height-1-origin.y)*(image->height-1-origin.y));
  24. }
  25. else if(origin.x<=center.x && origin.y>center.y)
  26. {
  27. distance=sqrt((image->width-1-origin.x)*(image->width-1-origin.x)+
  28. origin.y*origin.y);
  29. }
  30. else if(origin.x>center.x && origin.y<=center.y)
  31. {
  32. distance=sqrt(origin.x*origin.x+
  33. (image->height-1-origin.y)*(image->height-1-origin.y));
  34. }
  35. else if(origin.x>center.x && origin.y>center.y)
  36. {
  37. distance=sqrt(origin.x*origin.x+origin.y*origin.y);
  38. }
  39. double weightB=(b.val[0]-a.val[0])/distance;
  40. double weightG=(b.val[1]-a.val[1])/distance;
  41. double weightR=(b.val[2]-a.val[2])/distance;
  42. for(int i=0;i<image->width;i++)
  43. {
  44. for(int j=0;j<image->height;j++)
  45. {
  46. double dist=sqrt((i-origin.x)*(i-origin.x)+(j-origin.y)*(j-origin.y));
  47. uchar* ptr = &CV_IMAGE_ELEM(image,uchar,j,i*3);
  48. ptr[0] = cvRound(ptr[0]+weightB*dist);
  49. ptr[1] = cvRound(ptr[1]+weightG*dist);
  50. ptr[2] = cvRound(ptr[2]+weightR*dist);
  51. }
  52. }
  53. cvSaveImage( "radial.jpg", image );
  54. cvNamedWindow( "test", 1 );
  55. cvShowImage( "test", image );
  56. cvWaitKey();
  57. cvDestroyWindow("test");
  58. cvReleaseImage(&image);
  59. return 0;
  60. }

下圖是上面的代碼生成的效果圖。通過改寫上面代碼中的相關參數,主要是變量a,b和origin,可以生成更炫的漸變圖。

當修改為a=CV_RGB(0,255,0); b=CV_RGB(255,0,0);產生如下的圖像

當修改為a=CV_RGB(255,255,0);b=CV_RGB(0,0,255);origin=cvPoint(200,100);生成的圖像如下

Copyright © Linux教程網 All Rights Reserved