利用PyQt5中QLabel组件实现亚克力磨砂效果

 更新时间:2022年03月25日 09:52:56   作者:之一Yo  
Windows10 在 UWP 应用中支持亚克力画刷,可以在部件的底部绘制亚克力效果的背景图。本文将使用QLabel来模拟这个磨砂过程,感兴趣的可以了解一下

前言

Windows10 在 UWP 应用中支持亚克力画刷,可以在部件的底部绘制亚克力效果的背景图。下面我们使用 QLabel 来模拟这个磨砂过程。

实现方法

MSDN 文档中介绍了亚克力材料的配方,包括:高斯模糊、亮度混合、色调混合和噪声纹理。

高斯模糊

我们先来实现高斯模糊的效果,使用 scipy 可以很轻松的实现这个过程:

# coding:utf-8
import numpy as np
from PIL import Image
from PyQt5.QtGui import QPixmap
from scipy.ndimage.filters import gaussian_filter


def gaussianBlur(imagePath: str, blurRadius=18, brightFactor=1, blurPicSize: tuple = None) -> np.ndarray:
    """ 对图片进行高斯模糊处理

    Parameters
    ----------
    imagePath: str
        图片路径

    blurRadius: int
        模糊半径

    brightFactor:float
        亮度缩放因子

    blurPicSize: tuple
        高斯模糊前将图片缩放到指定大小,可以加快模糊速度

    Returns
    -------
    image: `~np.ndarray` of shape `(w, h, c)`
        高斯模糊后的图像
    """
    if not imagePath.startswith(':'):
        image = Image.open(imagePath)
    else:
        image = Image.fromqpixmap(QPixmap(imagePath))

    if blurPicSize:
        # 调整图片尺寸,减小计算量,还能增加额外的模糊
        w, h = image.size
        ratio = min(blurPicSize[0] / w, blurPicSize[1] / h)
        w_, h_ = w * ratio, h * ratio

        if w_ < w:
            image = image.resize((int(w_), int(h_)), Image.ANTIALIAS)

    image = np.array(image)

    # 处理图像是灰度图的情况
    if len(image.shape) == 2:
        image = np.stack([image, image, image], axis=-1)

    # 对每一个颜色通道分别磨砂
    for i in range(3):
        image[:, :, i] = gaussian_filter(
            image[:, :, i], blurRadius) * brightFactor

    return image

亚克力纹理

接下来在 QLabel 上面绘制出亮度混合、色调混合和噪声纹理,一般色调混合使用的颜色是图像的主题色,可以用 colorthief 库提取,这里就不赘述了:

class AcrylicTextureLabel(QLabel):
    """ 亚克力纹理标签 """

    def __init__(self, tintColor: QColor, luminosityColor: QColor, noiseOpacity=0.03, parent=None):
        """
        Parameters
        ----------
        tintColor: QColor
            RGB 主色调

        luminosityColor: QColor
            亮度层颜色

        noiseOpacity: float
            噪声层透明度

        parent:
            父级窗口
        """
        super().__init__(parent=parent)
        self.tintColor = QColor(tintColor)
        self.luminosityColor = QColor(luminosityColor)
        self.noiseOpacity = noiseOpacity
        self.noiseImage = QImage('resource/noise.png')
        self.setAttribute(Qt.WA_TranslucentBackground)

    def setTintColor(self, color: QColor):
        """ 设置主色调 """
        self.tintColor = color
        self.update()

    def paintEvent(self, e):
        """ 绘制亚克力纹理 """
        acrylicTexture = QImage(64, 64, QImage.Format_ARGB32_Premultiplied)

        # 绘制亮度层
        acrylicTexture.fill(self.luminosityColor)

        # 绘制主色调
        painter = QPainter(acrylicTexture)
        painter.fillRect(acrylicTexture.rect(), self.tintColor)

        # 绘制噪声
        painter.setOpacity(self.noiseOpacity)
        painter.drawImage(acrylicTexture.rect(), self.noiseImage)

        acrylicBrush = QBrush(acrylicTexture)
        painter = QPainter(self)
        painter.fillRect(self.rect(), acrylicBrush)

用到的噪声图像如下图所示:

亚克力标签

最后在 QLabel 上叠加磨砂图像和亚克力纹理,可以通过 Image.toqpixmap() 将 Image 转换为 QPixmap

class AcrylicLabel(QLabel):
    """ 亚克力标签 """

    def __init__(self, blurRadius: int, tintColor: QColor, luminosityColor=QColor(255, 255, 255, 0),
                 maxBlurSize: tuple = None, parent=None):
        """
        Parameters
        ----------
        blurRadius: int
            磨砂半径

        tintColor: QColor
            主色调

        luminosityColor: QColor
            亮度层颜色

        maxBlurSize: tuple
            最大磨砂尺寸,越小磨砂速度越快

        parent:
            父级窗口
        """
        super().__init__(parent=parent)
        self.imagePath = ''
        self.blurPixmap = QPixmap()
        self.blurRadius = blurRadius
        self.maxBlurSize = maxBlurSize
        self.acrylicTextureLabel = AcrylicTextureLabel(
            tintColor, luminosityColor, parent=self)

    def setImage(self, imagePath: str):
        """ 设置图片 """
        if imagePath == self.imagePath:
            return

        self.imagePath = imagePath
        image = Image.fromarray(gaussianBlur(
            imagePath, self.blurRadius, 0.85, self.maxBlurSize))
        self.blurPixmap = image.toqpixmap()  # type:QPixmap
        self.setPixmap(self.blurPixmap)
        self.adjustSize()

    def setTintColor(self, color: QColor):
        """ 设置主色调 """
        self.acrylicTextureLabel.setTintColor(color)

    def resizeEvent(self, e):
        super().resizeEvent(e)
        self.acrylicTextureLabel.resize(self.size())
        self.setPixmap(self.blurPixmap.scaled(
            self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))

测试

下面是测试用的埃罗芒阿老师:

代码如下:

# coding:utf-8
import sys

from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication

from acrylic import AcrylicLabel


app = QApplication(sys.argv)
w = AcrylicLabel(20, QColor(105, 114, 168, 102))
w.setImage('resource/ClariS_ヒトリゴト (アニメ盤).jpg')
w.show()
app.exec_()

结果如下:

到此这篇关于利用PyQt5中QLabel组件实现亚克力磨砂效果的文章就介绍到这了,更多相关PyQt5 QLabel磨砂效果内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • pymongo如何通过oplog获取数据(mongodb)

    pymongo如何通过oplog获取数据(mongodb)

    使用MongoDB的oplog(操作日志)进行数据同步是高级的用法,主要用于复制和故障恢复,这篇文章主要介绍了pymongo通过oplog获取数据(mongodb),需要的朋友可以参考下
    2023-09-09
  • Django Admin 实现外键过滤的方法

    Django Admin 实现外键过滤的方法

    下面小编就为大家带来一篇Django Admin 实现外键过滤的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • Python图像处理库PIL中图像格式转换的实现

    Python图像处理库PIL中图像格式转换的实现

    这篇文章主要介绍了Python图像处理库PIL中图像格式转换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • Python中文件操作简明介绍

    Python中文件操作简明介绍

    这篇文章主要介绍了Python中文件操作简明介绍,本文讲解了打开文件、读取方法、写入方法、文件内移动、文件迭代、关闭文件、截取文件等内容,并给出了一个完整操作实例,需要的朋友可以参考下
    2015-04-04
  • python executemany的使用及注意事项

    python executemany的使用及注意事项

    这篇文章主要介绍了python executemany的使用及注意事项,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-03-03
  • Python Spyder 调出缩进对齐线的操作

    Python Spyder 调出缩进对齐线的操作

    这篇文章主要介绍了Python Spyder 调出缩进对齐线的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Python实现从多表格中随机抽取数据

    Python实现从多表格中随机抽取数据

    这篇文章主要介绍了如何基于Python语言实现随机从大量的Excel表格文件中选取一部分数据,并将全部文件中随机获取的数据合并为一个新的Excel表格文件的方法,希望对大家有所帮助
    2023-05-05
  • Python3自动生成MySQL数据字典的markdown文本的实现

    Python3自动生成MySQL数据字典的markdown文本的实现

    这篇文章主要介绍了Python3自动生成MySQL数据字典的markdown文本的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • 基于python分析你的上网行为 看看你平时上网都在干嘛

    基于python分析你的上网行为 看看你平时上网都在干嘛

    这篇文章主要介绍了基于python分析你的上网行为 看看你平时上网都在干嘛,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • python3 pandas 读取MySQL数据和插入的实例

    python3 pandas 读取MySQL数据和插入的实例

    下面小编就为大家分享一篇python3 pandas 读取MySQL数据和插入的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04

最新评论