Because this is the first article, I will first briefly explain how to achieve grayscale image. Graying a picture means converting a color image into a grayscale image. In the RGB model, one pixel of RGB is converted into a transitional color from black to white. The following are two methods for obtaining grayscale images.
1. Find the average value Y of the pixel RGB, and then assign this average value to the three components of R, G, and B.
2. According to the formula Y = 0.3R + 0.59G + 0.11B, where Y is the gray value. (If you are interested in the source of the specific formula, you can check it)
Before the image is grayed out, here is a program that can check the RGB of a pixel. The function is to display the RGB value of that point by left-clicking the mouse.
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
IMAGE img1;
int imagHight,imagWidth;
int main()
{
BYTE R;
BYTE G;
BYTE B; //读取像素点RGB
MOUSEMSG m; // 定义鼠标消息
// 读取图片至绘图窗口
loadimage(&img1, _T("D:\\testh.bmp"));//获取图片
imagHight = img1.getheight();
imagWidth = img1.getwidth(); //获取图片高度和宽度
initgraph(imagWidth,imagHight, SHOWCONSOLE);//设置绘图窗口和图片一样大 并且显示控制台窗口
putimage(0, 0, &img1);//显示图片
while(1)
{
// 获取一条鼠标消息
m = GetMouseMsg();
switch(m.uMsg)
{
case WM_LBUTTONDOWN:
//如果按下鼠标左键
R = GetRValue(getpixel(m.x,m.y));
G = GetGValue(getpixel(m.x,m.y));
B = GetBValue(getpixel(m.x,m.y));//获取RGB的三个分量值
printf("X:%3d Y:%3d R:%3d G:%3d B:%3d \n",m.x,m.y,R,G,B);//打印像素点位置和对应的RGB值
break;
case WM_RBUTTONUP:
return 0; // 按鼠标右键退出程序
}
}
closegraph();
}
Effect picture:
Now I give the first method grayscale program:
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
int Gray[1500][1000]; //存储图像的灰度值数组
IMAGE img1;
int imagHight,imagWidth;
int main()
{
int i,j;
// 读取图片至绘图窗口
loadimage(&img1, _T("D:\\testh.bmp"));
imagHight = img1.getheight();
imagWidth = img1.getwidth();
initgraph(imagWidth,imagHight);
putimage(0, 0, &img1);
_getch();
DWORD* pMem = GetImageBuffer();
for(i = 0; i <imagHight; i++)
{
for(j=0;j<imagWidth;j++)
{
*pMem = BGR(*pMem);//获取正确的RGB 因为显存与内存rgb存储方式不同
Gray[i][j] = (GetRValue(*pMem)+GetGValue(*pMem)+GetBValue(*pMem))/3; //取RGB平均值
*pMem = RGB(Gray[i][j],Gray[i][j],Gray[i][j]);
pMem++;
}
}
FlushBatchDraw();
_getch();
closegraph();
}
Original and renderings:
The second method is to change the
Gray[i][j] = (GetRValue(*pMem)+GetGValue(*pMem)+GetBValue(*pMem))/3; //取RGB平均值
Replace with
Gray[i][j] = GetRValue(*pMem)*0.3+GetGValue(*pMem)*0.59+GetBValue(*pMem)*0.11;
The effect chart is as follows:
The following are the RGB values of pixels after the first method and the second method respectively.