我的导师写道“编写一个函数,将图像量化为 q 个灰度级。例如,如果 q=8,将 0-31 之间的每个像素替换为 0,32-63 之间的每个像素替换为 32,...,以及 224- 255 乘 224。”到目前为止,这是我的代码。
void quantize (int image[][MAXHEIGHT], int width, int height, int q)
{
const int temp = 256 / q;
int startPixel, endPixel;
int indicator = temp; // where the pixels are divided, 0-31, 32-63, etc if q = 8
while (indicator <= 256)
{
startPixel = indicator - temp;
endPixel = indicator - 1;
cout << "start value is " << startPixel << " and end value is " << endPixel << endl;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
if ((image[col][row] > startPixel) && (image[col][row] <= endPixel));
{
image[col][row] = startPixel;
}
}
}
indicator += temp;
}
}
当我尝试量化图像时,它要么变成全白,要么变成全黑。我认为我错误地循环了此函数,但不确定如何修复它。
最佳答案
错误在您的函数的 header 中。您正在传递图像的拷贝,因此您的拷贝在函数内部进行了修改,但不会在函数外进行修改。此外,代码可以简化很多。我给你我的方法:
void quantize (int **image, int width, int height, int q)
{
const int r = 256 / q; // Ensure your image is on [0 255] range
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
image[col][row] = (int) (image[col][row] / r);
}
关于c++ - 量化图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36680330/