本文主要说明在win10笔记本上如何构建pipenv虚拟环境,然后利用AIGC工具快速构建图像分类器,最后利用pyinstaller打包生成exe可执行文件,以图文相结合的方式详细说明,供大家参考。
1、安装pipenv虚拟环境管理工具
pip install pipenv
2、在某目录下创建一个虚拟环境
进入项目目录(比如D:\devCode\d2l-zh\pytorch\learning-d2l\pyqt_img_cls),然后在地址栏输入cmd,进入Windows命令行中,
运行pipenv install命令
两点需要说明:
(1)python使用的版本:默认的python版本
(2)虚拟环境位置:存放虚拟环境的目录默认指定是C:\Users\xxx.virtualenvs目录下,可通过添加系统环境变量来调整存放目录,小编把存放路径改为D:\devCode\pipenv,所以可以看到上图中的路径为虚拟环境位置:D:\devCode\pipenv\Screen-amTXFjUr。
修改虚拟环境存放位置,需要在win系统环境变量下,增加WORKON_HOME和对应的路径。
运行完pipenv install命令后,可以在当前目录下看到已经创建 Pipfile和Pipfile.lock两个文件。
3、修改pipenv的镜像源
(1)修改Pipfile文件
将url = "pypi.org/simple"改为ur... = "pypi.tuna.tsinghua.edu.cn/simple" (2)修改Pipfile.lock文件
将Pipfile.lock中的"url": "pypi.org/simple",改为 "url": "pypi.tuna.tsinghua.edu.cn/simple",
4、运行pipenv shell激活虚拟环境安装依赖包
(1)安装pyqt5
pipenv install pyqt5
(2)安装pyqt5-tools
pipenv install pyqt5-tools
(3)安装pytorch
pipenv install torch==1.13.1
(4)安装torchvision
pipenv install torchvision==0.14.1
5、在pycharm中给项目配置安装好的pipenv虚拟环境
选择File-->setting
6、利用AIGC工具生成一个简单的图像分离器应用程序
最终的效果如下,里面主要用了resnet18分类模型,用pyqt5作为GUI界面进行交互 整体代码如下:
python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout, QFileDialog
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
from torchvision import models, transforms
from PIL import Image
import torch
from urllib import request
import os
class ImageClassifierApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
self.download_resnet18_model()
def init_ui(self):
self.setWindowTitle('Image Classifier App')
self.image_label = QLabel(self)
self.image_label.setAlignment(Qt.AlignCenter)
self.result_label = QLabel(self)
self.result_label.setAlignment(Qt.AlignCenter)
self.load_image_button = QPushButton('Load Image', self)
self.load_image_button.clicked.connect(self.load_image)
self.classify_button = QPushButton('Classify Image', self)
self.classify_button.clicked.connect(self.classify_image)
layout = QVBoxLayout()
layout.addWidget(self.load_image_button)
layout.addWidget(self.image_label)
layout.addWidget(self.classify_button)
layout.addWidget(self.result_label)
self.setLayout(layout)
def load_image(self):
file_dialog = QFileDialog()
file_path, _ = file_dialog.getOpenFileName(self, 'Open Image', '', 'Images (*.png *.jpg *.jpeg)')
if file_path:
pixmap = QPixmap(file_path)
self.image_label.setPixmap(pixmap)
self.image_label.show()
self.image_path = file_path
def download_resnet18_model(self):
model_path = "resnet18.pth"
if not os.path.exists(model_path):
print("Downloading ResNet18 model...")
url = "https://download.pytorch.org/models/resnet18-5c106cde.pth"
request.urlretrieve(url, model_path)
def classify_image(self):
if hasattr(self, 'image_path'):
image = Image.open(self.image_path)
model_path = "resnet18.pth"
resnet18 = models.resnet18(weights=None)
resnet18.load_state_dict(torch.load(model_path))
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = transform(image)
input_batch = input_tensor.unsqueeze(0)
resnet18.eval()
with torch.no_grad():
output = resnet18(input_batch)
_, predicted_idx = torch.max(output, 1)
class_names = self.get_imagenet_classes()
result = f"Predicted Class: {class_names[predicted_idx.item()]}"
self.result_label.setText(result)
else:
self.result_label.setText("Please load an image first.")
def get_imagenet_classes(self):
classes_path = "imagenet_classes.txt"
if not os.path.exists(classes_path):
print("Downloading ImageNet classes file...")
url = "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json"
request.urlretrieve(url, classes_path)
with open(classes_path, "r") as file:
classes = [line.strip() for line in file.readlines()]
return classes
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ImageClassifierApp()
window.show()
sys.exit(app.exec_())
7、打包exe
安装打包工具
运行pyinstaller -F img_cls_pyqt.py命令,进行打包
打包完成后,可以在当前目录下面生成一个dist文件夹,然后里面有一个exe文件
然后把imagenet_classes.txt和resnet18.pth两个依赖文件拷贝到dist目录,双击exe文件运行,然后选择一张图片,点击分类效果如下。
本文完毕,希望对您有帮助!