#include <iostream>
#include <atlimage.h>
using namespace std;
typedef struct
{
int x;
int y;
} point;//点
typedef struct
{
point leftup;
point rightdown;
} rect;//两个点构成矩形
//对比点是否是要找的颜色
bool findcolor(int* color, int* rgbadd, int colorcount)
{
for(int i =0 ; i < colorcount ; i++)
{
if(color[i] != rgbadd[i])
{
return false;
}
}
return true;
}
//计算点的rgb数值
int rgbaddfunc(byte* pRealData, int pit, point rgbpoint, int bitCount)
{
int rgb = (int)(*(pRealData + pit * rgbpoint.y + rgbpoint.x * bitCount + 2)) +
(int)(*(pRealData + pit * rgbpoint.y + rgbpoint.x * bitCount + 1)) +
(int)(*(pRealData + pit * rgbpoint.y + rgbpoint.x * bitCount));
return rgb;
}
//找色函数,点的数量为pointcount
void FindpointcountColor(HWND hWnd, int* color, rect range, point* offset, int pointcount, point& result)
{
HDC hDCScreen = ::GetDC(hWnd);
int nBitPerPixel = GetDeviceCaps(hDCScreen, BITSPIXEL);//获取到每个像素的bit数目
CImage m_MyImage;
m_MyImage.Create(range.rightdown.x, range.rightdown.y, nBitPerPixel);
//使用bitblt 将屏幕的DC画布上的内容 拷贝到CImage上
BitBlt(m_MyImage.GetDC(), range.leftup.x, range.leftup.y, range.rightdown.x, range.rightdown.y, hDCScreen, 0, 0, SRCCOPY);
point *Allpoint = new point[pointcount];
int *rgbAdd = new int[pointcount];
byte* pRealData = (byte*)m_MyImage.GetBits();
int pit = m_MyImage.GetPitch();
int bitCount = m_MyImage.GetBPP() / 8;
for (int y = range.leftup.y; y < range.rightdown.y; y++) {
for (int x = range.leftup.x; x < range.rightdown.x; x++) {
for(int i = 0; i < pointcount; i++)
{
Allpoint[i].x = offset[i].x + x;
Allpoint[i].y = offset[i].y + y;
}
for(int i = 0; i < pointcount; i++)
{
rgbAdd[i] = rgbaddfunc(pRealData, pit, Allpoint[i], bitCount);
}
if (findcolor(color, rgbAdd, pointcount))
{
result.x = x;
result.y = y;
m_MyImage.ReleaseDC();
delete [] rgbAdd;
delete [] Allpoint;
return;
}
}
}
result.x = -1;
result.y = -1;
m_MyImage.ReleaseDC();
delete [] rgbAdd;
delete [] Allpoint;
}
int main()
{
//以三点找色为例
int rgb[3];
rgb[0] = 100 + 242 + 150;
rgb[1] = 100 + 242 + 150;
rgb[2] = 100 + 242 + 150;
rect findrect;
findrect.leftup.x = 0;
findrect.leftup.y = 0;
findrect.rightdown.x = 1920;
findrect.rightdown.y = 1080;
point offset[3];
offset[0].x = 0;
offset[0].y = 0;
offset[1].x = 0;
offset[1].y = 0;
offset[2].x = 0;
offset[2].y = 0;
point result;
FindColor(NULL, rgb, findrect, offset, 3, result);
cout << "找到颜色点的坐标为:" << result.x << "," <<result.y << endl;
return 0;
}
c++多点找色
于 2023-02-17 14:13:17 首次发布