cimg编程灰度转换示例

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值