如果新图像中的原始像素为黑色,则Qt绘制一个蓝色像素

Qt draw a blue pixel if the original pixel was black in a new image

本文关键字:像素 绘制 Qt 蓝色 一个 黑色 新图像 图像 原始 如果      更新时间:2023-10-16

我写了一些代码,应该可以生成一个新图像。我的背景图像有黑色区域,当for循环出现在黑色像素上时,它应该在新图像中绘制蓝色图像,否则它应该只绘制原始像素。本以为我可以这样做,但程序一直在运行。

   QApplication a(argc, argv);
int c, m, y, k, al;
QColor color;
QColor drawColor;
QImage background;
QImage world(1500, 768, QImage::Format_RGB32);
QSize sizeImage;
int height, width;
background.load("Background.jpg");
world.fill(1);
QPainter painter(&background);
sizeImage = background.size();
width = sizeImage.width();
height = sizeImage.height();
for(int i = 0; i < height; i++)
{
    for(int z = 0; z < width; z++)
    {
        color = QColor::fromRgb (background.pixel(i,z) );
        color.getCmyk(&c,&m,&y,&k,&al);
        if(c == 0 && m == 0 && y == 0 && k == 0) //then we have black as color and then we draw the color blue
        {
            drawColor.setBlue(255);
            painter.setPen(drawColor);
            painter.drawPoint(i,z);
        }
    }
}

//adding new image to the graphicsScene
QGraphicsPixmapItem item( QPixmap::fromImage(background));
QGraphicsScene* scene = new QGraphicsScene;
scene->addItem(&item);
QGraphicsView view(scene);
view.show();

是我的for循环错了还是我的画家?它说QImage::pixel:坐标(292981)超出范围,但对于太多像素,它也不够快。

正如评论中所指出的,逐个绘制像素可能非常缓慢。即使是逐像素访问也可能相当缓慢。例如,以下可能更快,但仍然不是很好:

  const QRgb black = 0;
  const QRgb blue = 255;
  for(int y = 0; y < height; y++) {
    for(int x = 0; x < width; x++) {
      if (background.pixel(x,y) == black) {
         background.SetPixel(blue);
      }
    }
  }

更快的解决方案包括通过scanline()直接进行位运算。您可能想先调用convertToFormat(),这样就不需要处理不同的可能扫描线格式。

作为一个创造性的破解,调用createMaskFromColor使所有黑色像素透明,然后在蓝色背景上绘制。