具体代码,p图功能用函数封装
时间: 2024-02-24 16:56:26 浏览: 100
好的,以下是一个可能的实现:
```python
import cv2
import numpy as np
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QFileDialog
class P图软件(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('P图软件')
# 上传图片部分
self.upload_label = QLabel('上传图片', self)
self.upload_label.move(50, 50)
self.upload_button = QPushButton('上传', self)
self.upload_button.move(50, 80)
self.upload_button.clicked.connect(self.upload_image)
# P图部分
self.ptu_label = QLabel('P图', self)
self.ptu_label.move(50, 200)
self.gray_button = QPushButton('转为灰度图', self)
self.gray_button.move(50, 230)
self.gray_button.clicked.connect(self.to_gray)
self.bright_button = QPushButton('调整亮度', self)
self.bright_button.move(50, 260)
self.bright_button.clicked.connect(self.adjust_brightness)
self.invert_button = QPushButton('反色处理', self)
self.invert_button.move(50, 290)
self.invert_button.clicked.connect(self.invert_colors)
# 保存结果部分
self.save_label = QLabel('保存结果', self)
self.save_label.move(50, 400)
self.save_button = QPushButton('保存', self)
self.save_button.move(50, 430)
self.save_button.clicked.connect(self.save_image)
# 显示图片
self.image_label = QLabel(self)
self.image_label.move(300, 50)
self.image_label.resize(400, 400)
self.show()
def upload_image(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
filename, _ = QFileDialog.getOpenFileName(self, '上传图片', '',
'Image files (*.jpg *.jpeg *.png *.bmp *.gif)', options=options)
if filename:
self.image = cv2.imread(filename)
self.show_image()
def show_image(self):
height, width, channel = self.image.shape
bytesPerLine = 3 * width
qImg = QPixmap.fromImage(QImage(self.image.data, width, height, bytesPerLine, QImage.Format_RGB888))
self.image_label.setPixmap(qImg)
def to_gray(self):
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
self.show_image()
def adjust_brightness(self):
alpha = 1.5 # 亮度调整系数
beta = 50 # 亮度调整偏移量
self.image = cv2.convertScaleAbs(self.image, alpha=alpha, beta=beta)
self.show_image()
def invert_colors(self):
self.image = cv2.bitwise_not(self.image)
self.show_image()
def save_image(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
filename, _ = QFileDialog.getSaveFileName(self, '保存图片', '',
'Image files (*.jpg *.jpeg *.png *.bmp *.gif)', options=options)
if filename:
cv2.imwrite(filename, self.image)
if __name__ == '__main__':
app = QApplication([])
p = P图软件()
app.exec_()
```
这个代码中,我们使用 PyQt5 库创建了一个简单的图形界面。我们添加了上传图片、P图和保存结果三个部分,分别包含了几个常用的 P 图功能,如转为灰度图、调整亮度、反色处理等。
注意,我们将 P 图功能封装成了独立的函数,例如 `to_gray()`、`adjust_brightness()` 和 `invert_colors()`。这使得代码更加清晰和易于维护。
希望这个代码可以帮助你完成你的 P 图软件项目!
阅读全文