这里只讨论对图像像素的处理,cimage类的具体用法查相关资料
#include <atlimage.h> //VS2010以后不用加这个
……………………
CImage m_Image; //或CImage* m_Image; 下面例子程序我用的CImage m_Image; 只是一个用成员选择符,一个用指针操作,效率上可能有所差异
下面是3种方法:
一、用Cimage类的成员函数进行处理
这里假设你已经加载了图像位图,并与CImage对象m_Image相关联。相关成员函数主要有:
GetPixel 返回像素颜色
SetPixel 设置像素颜色
如:m_Image.SetPixel( i-1, j-1, RGB(rr,gg,bb));
SetPixelRGB 设置像素的红绿蓝
如:m_Image.SetPixelRGB(x,y,avg,avg,avg);
SetColorTable 设置调色板颜色分量(红、绿、蓝)值
GetWidth 宽度(以像素为单位)
GetHeight 高度
1、程序示例
1)一个双线性插值放大程序。
if (m_Image.IsNull())
return;
// 创建对话框
DlgInterpolation TranPara;
//显示对话框,提示用户设定量
if (TranPara.DoModal() != IDOK)
return;
int k=TranPara.m_inter;
BeginWaitCursor();
CImage m_Image1;
if (! m_Image1.IsNull())
{
m_Image1.Destroy();
}
m_Image1.Create( m_Image.GetWidth()*k, m_Image.GetHeight()*k, 24,0);
// 四个最临近象素的坐标
int x1, x2;
int y1, y2;
// 四个最临近象素值
unsigned char f1, f2, f3, f4;
// 二个插值中间值
unsigned char f12, f34;
//计算结果
int fr,fb,fg;
double epsilon = 0.001;
COLORREF pixel11,pixel12,pixel21,pixel22;
int nHeight1 = m_Image1.GetHeight();
int nWidth1 = m_Image1.GetWidth();
int nHeight = m_Image.GetHeight();
int nWidth = m_Image.GetWidth();
double m=((double)nWidth1-1)/((double)nWidth-1);
for (int i=0; i<nWidth1; i++)
{
for (int j=0; j<nHeight1; j++)
{
double x=double((double)i/m);
double y=double((double)j/m);
//计算四个最临近象素的坐标,+1向右下方移动
x1 = (int) x;
x2 = x1 + 1;
y1 = (int) y;
y2 = y1 + 1;
if( (x < 0) || (x > nWidth - 1) || (y < 0) || (y > nHeight - 1))
{
//要计算的点不在源图范围内,返回-1
continue;
}
else
{
if (fabs(x - nWidth + 1) <= epsilon )
{
// 要计算的点在图像右边缘上
if (fabs(y -nHeight + 1) <= epsilon)
{
// 要计算的点正好是图像最右下角那一个象素,直接返回该点象素值
pixel11 = m_Image.GetPixel(x1,y1);
f1 = (unsigned char)GetRValue(pixel11);
fr=(int)f1;
f1 = (unsigned char)GetGValue(pixel11);
fg=(int)f1;
f1 = (unsigned char)GetBValue(pixel11);
fb=(int)f1;
}
else
{
// 在图像右边缘上且不是最后一点,直接一次插值即可
pixel11 = m_Image.GetPixel(x1,y1);
pixel12 = m_Image.GetPixel(x1,y2);
f1 = (unsigned char)GetRValue(pixel11);
f3 = (unsigned char)GetRValue(pixel12);
fr= (int) (f1 + (y -y1) * (f3 - f1));
f1 = (unsigned char)GetGValue(pixel11);
f3 = (unsigned char)GetGValue(pixel12);
fg= (int) (f1 + (y -y1) * (f3 - f1));
f1 = (unsigned char)GetBValue(pixel11);
f3 = (unsigned char)GetBValue(pixel12);
fb= (int) (f1 + (y -y1) * (f3 - f1));
}
}
else if (fabs(y - nHeight + 1) <= epsilon)
{
// 要计算的点在图像下边缘上且不是最后一点,直接一次插值即可
pixel11 = m_Image.GetPixel(x1,y1);
pixel21 = m_Image.GetPixel(x2,y1);
f1 = (unsigned char)GetRValue(pixel11);
f2 = (unsigned char)GetRValue(pixel21);
fr=(int) (f1 + (x -x1) * (f2 - f1));
f1 = (unsigned char)GetGValue(pixel11);