python的工业过程控制场景模拟第五十篇:水力闸门液位流量数据,拟合水位—泄流量数学模型。
2026/8/3 17:58:50
作为一名自媒体作者,你可能经常需要拍摄商品测评视频。但手动剪辑和标注商品信息耗时耗力,这时候AI物体识别技术就能派上用场。ResNet18作为深度学习领域的"轻量级选手",特别适合预算有限的新手:
想象一下,这就像用手机拍专业级照片——不需要昂贵的单反相机,也能获得不错的效果。
在CSDN算力平台操作非常简单:
💡 提示
如果找不到特定镜像,可以搜索"PyTorch基础镜像",然后通过pip安装torchvision库(已包含ResNet18模型)
选择按量计费模式,配置建议:
GPU类型:T4(性价比最高) 显存:4GB 镜像:PyTorch 1.12 + CUDA 11.3点击"立即创建",等待1-2分钟环境就绪。首次启动可能会稍慢,因为需要下载基础镜像。
将商品照片上传到环境中的/data目录。建议使用JPG格式,尺寸不超过1024x1024像素。
可以通过网页端直接上传,或者使用Python代码批量处理:
import os from PIL import Image def resize_images(input_dir, output_dir, size=(224,224)): os.makedirs(output_dir, exist_ok=True) for img_name in os.listdir(input_dir): img = Image.open(os.path.join(input_dir, img_name)) img = img.resize(size) img.save(os.path.join(output_dir, img_name)) resize_images('raw_images', 'data') # 调整图片尺寸适应模型输入新建Python文件object_detection.py,粘贴以下代码:
import torch import torchvision from torchvision import transforms from PIL import Image # 加载预训练模型 model = torchvision.models.resnet18(pretrained=True) model.eval() # 图像预处理 preprocess = 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] ) ]) # 加载类别标签 with open('imagenet_classes.txt') as f: classes = [line.strip() for line in f.readlines()] # 识别函数 def predict(img_path): img = Image.open(img_path) img_t = preprocess(img) batch_t = torch.unsqueeze(img_t, 0) with torch.no_grad(): out = model(batch_t) _, index = torch.max(out, 1) percentage = torch.nn.functional.softmax(out, dim=1)[0] * 100 return classes[index[0]], percentage[index[0]].item() # 示例使用 result, confidence = predict('data/test.jpg') print(f"识别结果: {result} (置信度: {confidence:.2f}%)")需要先下载ImageNet类别标签文件:
wget https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.txt -O imagenet_classes.txt运行脚本后会输出识别结果和置信度:
python object_detection.py典型输出示例:
识别结果: coffee mug (置信度: 92.37%)使用OpenCV将视频按秒拆分成图片帧:
import cv2 def video_to_frames(video_path, output_dir): vidcap = cv2.VideoCapture(video_path) success, image = vidcap.read() count = 0 while success: cv2.imwrite(f"{output_dir}/frame_{count:04d}.jpg", image) success, image = vidcap.read() count += 1 video_to_frames('test_video.mp4', 'video_frames')修改之前的识别脚本,增加批量处理功能:
import os def batch_predict(image_dir): results = [] for img_name in os.listdir(image_dir): if img_name.endswith(('.jpg', '.png')): result, confidence = predict(os.path.join(image_dir, img_name)) results.append((img_name, result, confidence)) return results frame_results = batch_predict('video_frames')将识别结果添加回视频:
def add_labels_to_video(input_video, output_video, results): cap = cv2.VideoCapture(input_video) fps = cap.get(cv2.CAP_PROP_FPS) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_video, fourcc, fps, (width, height)) frame_idx = 0 while cap.isOpened(): ret, frame = cap.read() if not ret: break if frame_idx < len(results): label = f"{results[frame_idx][1]} ({results[frame_idx][2]:.1f}%)" cv2.putText(frame, label, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2) out.write(frame) frame_idx += 1 cap.release() out.release() add_labels_to_video('test_video.mp4', 'output_video.mp4', frame_results)如果遇到CUDA out of memory错误,可以尝试:
batch_t = torch.unsqueeze(img_t, 0)中的batch sizetransforms.Resize(256)改为transforms.Resize(128)torch.cuda.empty_cache()现在就可以上传你的商品图片,体验AI物体识别的神奇效果!实测下来,从部署到出结果全程不超过10分钟,特别适合需要快速产出内容的自媒体作者。
💡获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。