在PyQt5中实现泛洪填充

问题描述 投票:1回答:1

我正在尝试实现相当于Paint,为此我需要填充。任何人都可以告诉如何使用PyQt5找出像素的颜色,并使用宽度搜索来找到类似的像素。然后将所有这些像素更改为新颜色。只是在tkinter中这是getpixel和putpixel。我想知道PyQt5是否这样做。如果有,那么我要求展示一些实施的例子。

附:你可以不用寻找像素,只展示如何拍摄和替换像素。

P.s.s.如果出现问题,我为我的英语道歉:

python python-3.x user-interface pyqt5 paint
1个回答
2
投票

我有an implementation of a Paint program here,其中包括一个洪水填充的例子。

不幸的是,它比你想象的要复杂一点。在Qt中从QImage读取一个像素是可能的,你可以这样做 -

QImage.pixel(x, y)       # returns a QRgb object
QImage.pixelColor(x, y)  # returns a QColor object

Basic algorithm

使用QImage.pixel(x,y)的基本森林火灾填充算法如下所示。我们首先将pixmap转换为QImage(如果需要)。

    image = self.pixmap().toImage()
    w, h = image.width(), image.height()
    x, y = e.x(), e.y()

    # Get our target color from origin.
    target_color = image.pixel(x,y)

然后我们定义一个函数,对于给定的位置查看所有周围的位置 - 如果它们还没有被查看 - 并测试它是命中还是未命中。如果它是一个命中,我们存储该像素以便稍后填充。

    def get_cardinal_points(have_seen, center_pos):
        points = []
        cx, cy = center_pos
        for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            xx, yy = cx + x, cy + y
            if (xx >= 0 and xx < w and
                yy >= 0 and yy < h and
                (xx, yy) not in have_seen):

                points.append((xx, yy))
                have_seen.add((xx, yy))

        return points

为了执行填充,我们创建了一个QPainter来写入我们的原始像素图。然后,从我们最初的x,y开始,我们迭代,检查基数点,并且 - 如果我们有匹配 - 将这些新的方块推到我们的队列中。我们去的时候填写任何匹配点。

    # Now perform the search and fill.
    p = QPainter(self.pixmap())
    p.setPen(QPen(self.active_color))

    have_seen = set()
    queue = [(x, y)]

    while queue:
        x, y = queue.pop()
        if image.pixel(x, y) == target_color:
            p.drawPoint(QPoint(x, y))
            queue.extend(get_cardinal_points(have_seen, (x, y)))

    self.update()

Performance

QImage.pixel()可能很慢,所以直接在QImage上面的读/写实现对于非常大的图像来说并不可行。在那之后,它将开始花费几秒钟来填充该区域。

我使用的解决方案是将要填充的区域转换为bytes。每个像素有4个字节(RGBA)。这为我们提供了一种可以更快地与之交互的数据结构。

    image = self.pixmap().toImage() # Convert to image if you have a QPixmap
    w, h = image.width(), image.height()
    s = image.bits().asstring(w * h * 4)

接下来,我们需要找到当前位置的3字节(RGB)值。使用我们的数据结构,我们创建一个自定义函数来检索我们的命中/未命中字节。

    # Lookup the 3-byte value at a given location.
    def get_pixel(x, y):
        i = (x + (y * w)) * 4
        return s[i:i+3]

    x, y = e.x(), e.y()
    target_color = get_pixel(x, y)

实际循环执行搜索输入中的所有点,如果找到匹配则将它们写入QPixmap

    # Now perform the search and fill.
    p = QPainter(self.pixmap())
    p.setPen(QPen(self.active_color))

    have_seen = set()
    queue = [(x, y)]

    while queue:
        x, y = queue.pop()
        if get_pixel(x, y) == target_color:
            p.drawPoint(QPoint(x, y))
            queue.extend(get_cardinal_points(have_seen, (x, y)))

    self.update()
© www.soinside.com 2019 - 2024. All rights reserved.