cimg编程灰度转换示例

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 05:09   20   0

Posted on December 21, 2012 by admin

In the below presented code a RGB jpeg image is loaded and converted to two different grayscale images using different formulas. The created images are displayed and stored as WindosBitmap(bmp) files.

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "CImg.h"
#include  <iostream>
using namespace cimg_library;
using namespace std;
 
int main() {
 
 //Construct image from reading an image file. 
 CImg<unsigned char> src("Tulips.jpg"); 
 
 int width = src.width();
 int height = src.height();
 int depth = src.depth();
 
 //New grayscale images.
 CImg<unsigned char> gray1(width,height,depth,1);
 CImg<unsigned char> gray2(width,height,depth,1);
 
 
 unsigned char r,g,b;
 unsigned char gr1 = 0;
 unsigned char gr2 = 0;
 
 /* Convert RGB image to grayscale image */
 for(int i=0;i<width;i++){
  for(int j=0;j<height;j++){
 
   //Return a pointer to a located pixel value. 
   r = src(i,j,0,0); // First channel RED
   g = src(i,j,0,1); // Second channel GREEN
   b = src(i,j,0,2); // Third channel BLUE
 
 
   //PAL and NTSC
   //Y = 0.299*R + 0.587*G + 0.114*B
   gr1 = round(0.299*((double)r) + 0.587*((double)g) + 0.114*((double)b));
 
   //HDTV 
   //Y = 0.2126*R + 0.7152*G + 0.0722*B
   gr2 = round(0.2126*((double)r) + 0.7152*((double)g) + 0.0722*((double)b));
 
   gray1(i,j,0,0) = gr1;
   gray2(i,j,0,0) = gr2;
  }
 
 }
 
 //save the new grayscale images
 gray1.save("gray1.bmp");
 gray2.save("gray2.bmp");
 
 //show all images
 (src,gray1,gray2).display("RGB to Grayscale");
 
 
 return 0;
}

The makefile:

all: convert.cpp CImg.h
 g++ CImg.h convert.cpp -lgdi32 -o grayscale

The output:

This entry was posted in C++, CImg by admin. Bookmark the permalink.


来源:http://sorj.de/?p=168

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP