单色位图均值滤波MFC代码实现
时间: 2023-12-11 13:10:24 浏览: 75
以下是单色位图均值滤波的MFC代码实现:
void CImageProcessDlg::OnBnClickedButtonMeanFilter()
{
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("Bitmap Files(*.bmp)|*.bmp|All Files(*.*)|*.*||"));
if (dlg.DoModal() == IDOK)
{
CString filePath = dlg.GetPathName();
CImage img;
img.Load(filePath);
if (img.IsNull())
{
MessageBox(_T("Failed to load image!"));
return;
}
if (img.GetBPP() != 8)
{
MessageBox(_T("The image must be 8-bit grayscale!"));
return;
}
// Get image data
BYTE* pData = (BYTE*)img.GetBits();
int width = img.GetWidth();
int height = img.GetHeight();
int pitch = img.GetPitch();
// Allocate memory for filtered image
BYTE* pFilteredData = new BYTE[width * height];
// Apply mean filter
int kernelSize = 3;
int kernelRadius = kernelSize / 2;
for (int y = kernelRadius; y < height - kernelRadius; y++)
{
for (int x = kernelRadius; x < width - kernelRadius; x++)
{
// Compute mean value
int sum = 0;
for (int dy = -kernelRadius; dy <= kernelRadius; dy++)
{
for (int dx = -kernelRadius; dx <= kernelRadius; dx++)
{
int pixelValue = pData[(y + dy) * pitch + (x + dx)];
sum += pixelValue;
}
}
int meanValue = sum / (kernelSize * kernelSize);
// Set filtered pixel value
pFilteredData[y * pitch + x] = meanValue;
}
}
// Create filtered image
CImage filteredImg;
filteredImg.Create(width, height, 8);
BYTE* pFilteredBits = (BYTE*)filteredImg.GetBits();
memcpy(pFilteredBits, pFilteredData, width * height);
// Save filtered image
CString filteredFilePath = dlg.GetPathName();
filteredFilePath.Insert(filteredFilePath.ReverseFind('.'), _T("_mean_filtered"));
filteredImg.Save(filteredFilePath, Gdiplus::ImageFormatBMP);
// Cleanup
delete[] pFilteredData;
}
}
阅读全文