Qt/PyQt(/其他?):如何更改像素图中的特定颜色?
如何更改像素图中的特定颜色?例如,我有一个包含白色和黑色像素的像素图,我想将所有白色像素更改为蓝色,但保留黑色像素。或者也许将黑色更改为白色,将白色更改为蓝色...[我正在 Qt/PyQt 中寻找解决方案,但也许这是关于如何处理/组合像素图的一般问题。]
How do I change specific colors in a pixmap? For example, I have a pixmap with white and black pixels, and I want to change all white pixels to blue, but leave the black ones alone. Or maybe change the black to white and the white to blue... [I am searching for a solution in Qt/PyQt, but maybe this is a general question as to how pixmaps are handled/composed.]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
createMaskFromColor
为白色像素创建位图,然后使用drawPixmap
用另一种颜色覆盖它们。请注意,
createMaskFromColor
会将像素图转换为QImage
,因此如果可能的话,您应该尝试直接使用QImage
。You can use
createMaskFromColor
to create a bitmap for the white pixels, then usedrawPixmap
to overwrite them with another color.Note that
createMaskFromColor
is going to convert the pixmap to aQImage
, so you should try to use aQImage
directly, if possible.有几个人问如何在不使用掩码的情况下完成位级操作(改变颜色)。为此,我们需要知道如何直接读取和设置像素。 QImage 就是为此类像素级操作而设计的,而标签和其他 QWidget 则需要 QPixmap。因此,我们还必须知道如何在 QPixmap 和 QImage 之间进行转换。
这是一个 PyQt6 示例(在 Windows 机器上用 Python 编写),它从头开始创建 QImage,使用 QPainter 绘制一些彩色圆圈,在屏幕上显示“之前”图像,然后检查每个像素,记录每个红色像素的计数,并将每个红色像素更改为白色,同时忽略所有其他颜色。我知道这段代码很丑陋。我按原样提供它是因为没有其他人提出一个例子来回答最初的问题。请将此代码视为启动您更深入研究的地方,并原谅其中的缺点。 -科学_1
A couple of people have asked how bit-level manipulation (changing colors) can be done without using a mask. For this, we need to know how to read and set pixels directly. QImage is designed for just such pixel-level manipulation, while QPixmaps are needed for labels and other QWidgets. So we also must know how to convert from QPixmaps to QImages and back again.
Here is a PyQt6 example (written in Python on a Windows machine) that creates a QImage from scratch, uses QPainter to draw some colored circles, shows the 'before' image on the screen, then examines each pixel, keeping count of each red pixel, and changes each red pixel to white while ignoring all other colors. I know this code is ugly. I offer it as-is because no one else has come forward with an example that answers the original question. Please consider this code a place to launch your deeper studies, and forgive the warts. -Science_1