#include <graphics.h>
#include <conio.h>
// 是否为边缘点
// b 灰度差阈值
bool isEdgePoint(int x, int y, int b)
{
POINT t[4] = { {0,1}, {0,-1}, {1,0}, {-1,0} };
int r = GetRValue(getpixel(x, y));
for (int i=0; i<4; i++)
{
if (GetRValue(getpixel(x+t[i].x, y+t[i].y)) - r > b)
{
return true;
}
}
return false;
}
// 彩色图像转换为灰度图像
void ColorToGray(IMAGE *pimg)
{
DWORD *p = GetImageBuffer(pimg); // 获取显示缓冲区指针
COLORREF c;
// 逐个像素点读取计算
for(int i = pimg->getwidth() * pimg->getheight() - 1; i >= 0; i--)
{
c = BGR(p[i]);
c = (GetRValue(c) * 299 + GetGValue(c) * 587 + GetBValue(c) * 114 + 500) / 1000;
p[i] = RGB(c, c, c); // 由于是灰度值,无需再执行 BGR 转换
}
}
void ImageProcess()
{
IMAGE img;
IMAGE imgGray;
const int b = 60;
loadimage(&img, "./img.jpg");
imgGray = img;
int w = img.getwidth();
int h = img.getheight();
POINT* pEdge = new POINT[w * h];
int sum;
ColorToGray(&imgGray);
SetWorkingImage(&imgGray);
for (int i=0; i<h; i++)
{
for (int j=0; j<w; j++)
{
if (isEdgePoint(j, i, b))
{
pEdge[sum] = {j, i};
sum++;
}
}
}
SetWorkingImage();
while(true)
{
putimage(0, 0, &img);
getch();
for (int i=0; i<sum; i++)
{
putpixel(pEdge[i].x, pEdge[i].y, RED);
}
getch();
}
}
int main()
{
initgraph(640, 480);
ImageProcess();
getch();
closegraph();
}
灰度图像生成算法来自 https://codebus.cn/zhaoh/gray-filter