您的位置:首页 > 文旅 > 美景 > qt生成一幅纯马赛克图像

qt生成一幅纯马赛克图像

2024/10/6 10:38:53 来源:https://blog.csdn.net/u012342051/article/details/141265064  浏览:    关键词:qt生成一幅纯马赛克图像

由于项目需要,需生成一幅纯马赛克的图像作为背景,经过多次测试成功,记录下来。

方法一:未优化方法

1、代码:

#include <QImage>
#include <QDebug>
#include <QElapsedTimer>QImage generateMosaic(int width, int height, int blockSize) {QImage image(width, height, QImage::Format_RGB888);if (blockSize <= 0) {return QImage(); // 返回空图片或处理错误}// 确保blockSize是偶数,并且不会使图像尺寸变得太小blockSize = (blockSize % 2 == 0) ? blockSize : blockSize + 1;if (image.width() < blockSize || image.height() < blockSize) {return image; // 如果blockSize太大,直接返回原图}// 计算新图片的尺寸int newWidth = image.width() / blockSize * blockSize;int newHeight = image.height() / blockSize * blockSize;qDebug() << "newWidth = " << newWidth << ", newHeight = " << newHeight;//QImage newImage(newWidth, newHeight, image.format());// 遍历每个块for (int x = 0; x < newWidth; x += blockSize) {for (int y = 0; y < newHeight; y += blockSize) {// 计算块的平均颜色QColor averageColor = QColor(0, 0, 0); // 初始化平均颜色为黑色// 用平均颜色填充整个块if((y / blockSize) % 2 == 0) {if((x/blockSize) % 2 == 0) {averageColor = QColor(60,60,60);} else {averageColor = QColor(150,150,150);}} else {if((x/blockSize) % 2 == 0) {averageColor = QColor(150,150,150);} else {averageColor = QColor(60,60,60);}}for  (int bx = 0; bx < blockSize && x + bx < newWidth; ++bx) {for ( int by = 0; by < blockSize && y + by < newHeight; ++by) {image.setPixel(x+bx, y+by, qRgb(averageColor.red(), averageColor.blue(), averageColor.green()));}}}}return image;
}int main()
{QElapsedTimer elapsed_timer; elapsed_timer.start(); QImage mosicImage = generateMosaic(1280,960,40);qDebug() << "Used" << elapsed_timer.elapsed() << "milliseconds.";mosicImage.save("mosic.jpg");return 0;
}

2、效果:

运行结果

newWidth =  1280 , newHeight =  960
Used 19 milliseconds.

方法二:优化后方法

更优化的方法:

1、代码

#include <QImage>
#include <QDebug>
#include <QPainter>
#include <QElapsedTimer>QImage generateMosaic(int width, int height, QImage::Format format)
{QColor color_a(102, 102, 102); QColor color_b(128, 128, 128);QImage empty_image(width, height, format);empty_image.fill(color_a);QPainter empty_painter(&empty_image);int stride = 32;for (int i=0; i<empty_image.width(); i+=stride) {for (int j=0; j<empty_image.height(); j+=stride) {if ((i+j) % (2*stride) == 0) {empty_painter.fillRect(QRect(i, j, stride, stride), color_b);} else {empty_painter.fillRect(QRect(i, j, stride, stride), color_a);}}}return empty_image;
}int main()
{QElapsedTimer elapsed_timer; elapsed_timer.start(); QImage mosicImage = generateMosaic(1280,960,QImage::Format_RGB888);qDebug() << "Used" << elapsed_timer.elapsed() << "milliseconds.";mosicImage.save("mosic.jpg");return 0;
}

2、效果

运行效果

Used 4 milliseconds.

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com