imgcodecs_jpeg.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <opencv2/core.hpp>
  2. #include <opencv2/imgproc.hpp>
  3. #include <opencv2/imgcodecs.hpp>
  4. #include <iostream>
  5. #include <vector>
  6. using namespace std;
  7. using namespace cv;
  8. int main(int /*argc*/, const char** /* argv */ )
  9. {
  10. Mat framebuffer( 160 * 2, 160 * 5, CV_8UC3, cv::Scalar::all(255) );
  11. Mat img( 160, 160, CV_8UC3, cv::Scalar::all(255) );
  12. // Create test image.
  13. {
  14. const Point center( img.rows / 2 , img.cols /2 );
  15. for( int radius = 5; radius < img.rows ; radius += 3 )
  16. {
  17. cv::circle( img, center, radius, Scalar(255,0,255) );
  18. }
  19. cv::rectangle( img, Point(0,0), Point(img.rows-1, img.cols-1), Scalar::all(0), 2 );
  20. }
  21. // Draw original image(s).
  22. int top = 0; // Upper images
  23. {
  24. for( int left = 0 ; left < img.rows * 5 ; left += img.rows ){
  25. Mat roi = framebuffer( Rect( left, top, img.rows, img.cols ) );
  26. img.copyTo(roi);
  27. cv::putText( roi, "original", Point(5,15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 2, 4, false );
  28. }
  29. }
  30. // Draw lossy images
  31. top += img.cols; // Lower images
  32. {
  33. struct test_config{
  34. string comment;
  35. uint32_t sampling_factor;
  36. } config [] = {
  37. { "411", IMWRITE_JPEG_SAMPLING_FACTOR_411 },
  38. { "420", IMWRITE_JPEG_SAMPLING_FACTOR_420 },
  39. { "422", IMWRITE_JPEG_SAMPLING_FACTOR_422 },
  40. { "440", IMWRITE_JPEG_SAMPLING_FACTOR_440 },
  41. { "444", IMWRITE_JPEG_SAMPLING_FACTOR_444 },
  42. };
  43. const int config_num = 5;
  44. int left = 0;
  45. for ( int i = 0 ; i < config_num; i++ )
  46. {
  47. // Compress images with sampling factor parameter.
  48. vector<int> param;
  49. param.push_back( IMWRITE_JPEG_SAMPLING_FACTOR );
  50. param.push_back( config[i].sampling_factor );
  51. vector<uint8_t> jpeg;
  52. (void) imencode(".jpg", img, jpeg, param );
  53. // Decompress it.
  54. Mat jpegMat(jpeg);
  55. Mat lossy_img = imdecode(jpegMat, -1);
  56. // Copy into framebuffer and comment
  57. Mat roi = framebuffer( Rect( left, top, lossy_img.rows, lossy_img.cols ) );
  58. lossy_img.copyTo(roi);
  59. cv::putText( roi, config[i].comment, Point(5,155), FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 2, 4, false );
  60. left += lossy_img.rows;
  61. }
  62. }
  63. // Output framebuffer(as lossless).
  64. imwrite( "imgcodecs_jpeg_samplingfactor_result.png", framebuffer );
  65. return 0;
  66. }