Qt图像处理技术四:图像二值化
github
如果你觉得有用的话,期待你的小星星
实战应用项目:
github :https://github.com/dependon/simple-image-filter //纯qt图像处理项目(包括多种滤镜)
效果
原理
rgb
每一点取rgb的平均值,
当平均值>128,设置点为255,255,255
当平均值<128,设置点为0,0,0
源码(容易理解版)
QImage Binaryzation(const QImage &origin)
{
int width = origin.width();
int height = origin.height();
QImage newImg = QImage(width, height, QImage::Format_RGB888);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int gray = qGray(origin.pixel(x, y));
int newGray;
if (gray > 128)
newGray = 255;
else
newGray = 0;
newImg.setPixel(x, y, qRgb(newGray, newGray, newGray));
}
}
return newImg;
}
源码(相对上述源码快5-20倍,因为绕过了Qt每个取点的检测)
QImage Binaryzation(const QImage &img)
{
QImage imgCopy;
if (img.format() != QImage::Format_RGB888) {
imgCopy = QImage(img).convertToFormat(QImage::Format_RGB888);
} else {
imgCopy = QImage(img);
}
uint8_t *rgb = imgCopy.bits();
int newGray = 0;
int gray = 0;
int size = img.width() * img.height();
for (int i = 0; i < size ; i++) {
gray = (rgb[i * 3] + rgb[i * 3 + 1] + rgb[i * 3 + 2]) / 3;
if (gray > 128)
newGray = 255;
else
newGray = 0;
rgb[i * 3] = newGray;
rgb[i * 3 + 1] = newGray;
rgb[i * 3 + 2] = newGray;
}
return imgCopy;
}