首页 文章 精选 留言 我的

精选列表

搜索[SVG格式],共10000篇文章
优秀的个人博客,低调大师

使用YOLOv8进行汽车零部件分割,汽车部位分割数据集 3000多张,yolo格式(txt标签),分辨率640x640, 22类

![在这里插入图片描述](https://developer.qcloudimg.com/http-save/yehe-12490569/70b776d08a1a5dc62612e885dad51990.png) 使用YOLOv8进行汽车零部件分割和汽车部位分割。代码包括数据集准备、加载预训练模型、设置数据集路径、数据集配置、开始训练、模型评估、可视化训练结果、清理临时文件以及推理和显示结果。![在这里插入图片描述](https://developer.qcloudimg.com/http-save/yehe-12490569/7fd12fc944ca17b49ab7ab5d453e6c88.png) ![在这里插入图片描述](https://developer.qcloudimg.com/http-save/yehe-12490569/927b29aef9e58ecc54966e2a7bffd97e.png) ``` import os import random from pathlib import Path import shutil import torch from ultralytics import YOLO import cv2 import numpy as np from PIL import Image import tempfile import matplotlib.pyplot as plt import yaml # 1. 创建数据集配置文件 (data.yaml) def create_data_yaml(train_dir, val_dir, nc, names): data_config = { 'train': train_dir, 'val': val_dir, 'nc': nc, 'names': names } with open('data.yaml', 'w') as f: yaml.dump(data_config, f) # 2. 分割数据集 def split_dataset(data_dir, train_ratio=0.8): images = list(Path(data_dir).glob('*.jpg')) random.shuffle(images) num_train = int(len(images) * train_ratio) train_images = images[:num_train] val_images = images[num_train:] train_dir = Path(data_dir).parent / 'train' val_dir = Path(data_dir).parent / 'val' train_img_dir = train_dir / 'images' train_label_dir = train_dir / 'labels' val_img_dir = val_dir / 'images' val_label_dir = val_dir / 'labels' train_img_dir.mkdir(parents=True, exist_ok=True) train_label_dir.mkdir(parents=True, exist_ok=True) val_img_dir.mkdir(parents=True, exist_ok=True) val_label_dir.mkdir(parents=True, exist_ok=True) for img in train_images: label_path = img.with_suffix('.txt') shutil.copy(img, train_img_dir / img.name) shutil.copy(label_path, train_label_dir / label_path.name) for img in val_images: label_path = img.with_suffix('.txt') shutil.copy(img, val_img_dir / img.name) shutil.copy(label_path, val_label_dir / label_path.name) # 使用示例 split_dataset('./datasets/car_parts_dataset/images') # 3. 创建数据集配置文件 (data.yaml) create_data_yaml( train_dir='./datasets/car_parts_dataset/train/images', val_dir='./datasets/car_parts_dataset/val/images', nc=5, # 假设有5个类别 names=['part1', 'part2', 'part3', 'part4', 'part5'] # 替换为实际类别名称 ) # 4. 训练脚本 def train_model(dataset_config, epochs=100, imgsz=640, batch=16, name='car_parts_detection', project='runs/train'): # 设置随机种子以保证可重复性 torch.manual_seed(42) # 加载预训练的YOLOv8n模型 model = YOLO('yolov8n.pt') # 训练模型 results = model.train( data=dataset_config, epochs=epochs, imgsz=imgsz, batch=batch, name=name, project=project ) # 评估模型 metrics = model.val() # 保存最佳模型权重 best_model_weights = f'{project}/{name}/weights/best.pt' print(f"Best model weights saved to {best_model_weights}") return best_model_weights # 使用示例 best_model_weights = train_model('data.yaml') # 5. 可视化训练结果 def visualize_training_results(project_dir, run_name): # 加载训练好的模型 model = YOLO(f'{project_dir}/{run_name}/weights/best.pt') # 可视化训练结果 model.plot_results(save=True, save_dir=f'{project_dir}/{run_name}') # 使用示例 visualize_training_results('runs/train', 'car_parts_detection') # 6. 清理临时文件 def clean_temp_files(project_dir): temp_dirs = [ f'{project_dir}/wandb', f'{project_dir}/cache' ] for dir_path in temp_dirs: if os.path.exists(dir_path): shutil.rmtree(dir_path) print(f"Removed directory: {dir_path}") # 使用示例 clean_temp_files('runs/train/car_parts_detection') # 7. 推理脚本 def detect_image(model, image_path, conf_threshold=0.5): results = model.predict(image_path, conf=conf_threshold)[0] annotated_frame = annotate_image(image_path, results, model) return annotated_frame def detect_video(model, video_path, conf_threshold): cap = cv2.VideoCapture(video_path) frames = [] while cap.isOpened(): ret, frame = cap.read() if not ret: break results = model.predict(frame, conf=conf_threshold)[0] annotated_frame = annotate_image(frame, results, model) frames.append(annotated_frame) cap.release() return frames def detect_camera(model, conf_threshold): cap = cv2.VideoCapture(0) frames = [] while True: ret, frame = cap.read() if not ret: break results = model.predict(frame, conf=conf_threshold)[0] annotated_frame = annotate_image(frame, results, model) frames.append(annotated_frame) cv2.imshow('Camera Detection', annotated_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() return frames def annotate_image(image_path, results, model): frame = cv2.imread(image_path) for result in results.boxes.cpu().numpy(): r = result.xyxy[0].astype(int) cls = int(result.cls[0]) conf = result.conf[0] label = f"{model.names[cls]} {conf:.2f}" color = (0, 255, 0) cv2.rectangle(frame, (r[0], r[1]), (r[2], r[3]), color, 2) cv2.putText(frame, label, (r[0], r[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2) return frame # 使用示例 def main(): # 加载模型 model = YOLO(best_model_weights) # 动态调整置信度阈值 conf_threshold = 0.5 # 输入方式选择 input_type = "Image" # 可选: "Image", "Video", "Camera" if input_type == "Image": test_image_path = './datasets/car_parts_dataset/images/test_image.jpg' annotated_image = detect_image(model, test_image_path, conf_threshold) cv2.imwrite('annotated_test_image.jpg', annotated_image) plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() # 统计检测到的物体数量 results = model.predict(test_image_path, conf=conf_threshold)[0] class_counts = {} for result in results.boxes.cpu().numpy(): cls = int(result.cls[0]) class_name = model.names[cls] if class_name in class_counts: class_counts[class_name] += 1 else: class_counts[class_name] = 1 print("Detection Summary:") for class_name, count in class_counts.items(): print(f"{class_name}: {count}") elif input_type == "Video": test_video_path = './datasets/car_parts_dataset/videos/test_video.mp4' frames = detect_video(model, test_video_path, conf_threshold) for i, frame in enumerate(frames): cv2.imwrite(f'frame_{i}.jpg', frame) plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() elif input_type == "Camera": frames = detect_camera(model, conf_threshold) for i, frame in enumerate(frames): cv2.imwrite(f'camera_frame_{i}.jpg', frame) plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() if __name__ == "__main__": main() ![在这里插入图片描述](https://developer.qcloudimg.com/http-save/yehe-12490569/4cfe610d725ddd5c7e01aa961101ba13.png) ```![在这里插入图片描述](https://developer.qcloudimg.com/http-save/yehe-12490569/fc1a6d6f30f1664431006547cec65dd1.png) ![在这里插入图片描述](https://developer.qcloudimg.com/http-save/yehe-12490569/baccc62847a672f06d89f25f1970e228.png) 好的,以下是完整的代码,用于使用YOLOv8进行汽车零部件分割和汽车部位分割。代码包括数据集准备、加载预训练模型、设置数据集路径、数据集配置、开始训练、模型评估、可视化训练结果、清理临时文件以及推理和显示结果。 ### 完整项目代码 ### 文件结构 ``` car_parts_segmentation/ ├── main.py ├── datasets/ │ └── car_parts_dataset/ │ ├── yolo/ │ │ ├── labels/ │ │ │ ├── image1.txt │ │ │ ├── image2.txt │ │ │ └── … │ │ ├── train/ │ │ │ ├── images/ │ │ │ │ ├── image1.jpg │ │ │ │ ├── image2.jpg │ │ │ │ └── … │ │ │ └── labels/ │ │ │ ├── image1.txt │ │ │ ├── image2.txt │ │ │ └── … │ │ └── val/ │ │ ├── images/ │ │ │ ├── image1.jpg │ │ │ ├── image2.jpg │ │ │ └── … │ │ └── labels/ │ │ ├── image1.txt │ │ ├── image2.txt │ │ └── … │ └── images/ │ ├── image1.jpg │ ├── image2.jpg │ └── … ├── best_car_parts_yolov8.pt └── requirements.txt ``` ### 安装依赖项 首先,确保你已经安装了所有必要的依赖项。你可以通过以下命令安装: ```bash pip install -r requirements.txt ``` `requirements.txt` 内容如下: ``` opencv-python torch==2.0 ultralytics matplotlib pyyaml ``` ### 运行步骤总结 1. **克隆项目仓库**(如果有的话): ``` git clone https://github.com/yourusername/car_parts_segmentation.git cd car_parts_segmentation ``` 2. **安装依赖项**: ``` pip install -r requirements.txt ``` 3. **数据集准备**: - 如果数据集尚未分割,请运行数据集分割脚本。``` python main.py ``` - 确保数据集目录结构正确。 4. **训练模型**: ``` python main.py ``` 5. **评估模型**: 在训练脚本中,模型会在训练结束后自动进行评估。 6. **可视化训练结果**: ``` python main.py ``` 7. **清理临时文件**: ``` python main.py ``` 8. **推理测试**: ``` python main.py ``` ### 总结 以上是完整的基于YOLOv8的汽车零部件分割系统的代码实现。代码涵盖了从数据集准备、模型训练、评估、可视化训练结果、清理临时文件到推理和显示结果的所有步骤。希望这些详细的信息和代码能够帮助你顺利实施和优化你的汽车零部件分割系统。

优秀的个人博客,低调大师

知乎上有一个问题“在mfc框架中,有上面方法能直接将opencv2.0库中的Mat格式图片传递到Picture Control”中显示?

一直以来,我使用的方法都是shiqiyu在opencvchina上面提供的引入directshow,并且采用cvvimage和cameraDs的方法。这个方法虽然在xp/win7/win8下面都能够成果使用,但是一直以来我都没有动机去深入看一看这个方法。这次在知乎上面看到 jie wu 提出的“将Opencv窗口添加到PictureControl”中的方法,感到思路很好,进行了具体实现 http://pan.baidu.com/s/1nuixdhR 具体可以看代码,我帖一些主要代码 void CMfcRibbonTemplateView : :OnInitialUpdate() { CFormView : :OnInitialUpdate(); GetParentFrame() - >RecalcLayout(); ResizeParentToFit(); //根据控件的大小设置初始帧的大小 CRect rect; GetDlgItem(IDC_PBSRC) - >GetClientRect( &rect ); // 获取控件尺寸位置 m_lframe = Mat : :zeros(rect.Height(),rect.Width(),CV_8UC3); GetDlgItem(IDC_PBSRC) - >GetClientRect( &rect ); m_rframe = Mat : :zeros(rect.Height(),rect.Width(),CV_8UC3); //绑定Mat到Picturebox上去 namedWindow( "src",WINDOW_AUTOSIZE); HWND hWnd = (HWND)cvGetWindowHandle( "src"); HWND hParnt = : :GetParent(hWnd); : :SetParent(hWnd,GetDlgItem(IDC_PBSRC) - >m_hWnd); : :ShowWindow(hParnt,SW_HIDE); namedWindow( "dst",WINDOW_AUTOSIZE); hWnd = (HWND)cvGetWindowHandle( "dst"); hParnt = : :GetParent(hWnd); : :SetParent(hWnd,GetDlgItem(IDC_PBDEST) - >m_hWnd); : :ShowWindow(hParnt,SW_HIDE); } void CMfcRibbonTemplateView : :OnSize(UINT nType, int cx, int cy) { CFormView : :OnSize(nType, cx, cy); CWnd * pwndsrc = GetDlgItem(IDC_PBSRC); CWnd * pwnddst = GetDlgItem(IDC_PBDEST); //计算出长宽,这里的长宽是按照比例的,图像居中显示 int iblank = 15; //边界空余 int iwidth = cx / 2 -iblank * 2; int iheight =( int)(iwidth * 0. 75); if (pwndsrc - >GetSafeHwnd() && pwnddst - >GetSafeHwnd()){ pwndsrc - >MoveWindow(iblank,(cy -iheight) * 0. 4,iwidth,iheight); pwnddst - >MoveWindow(cx / 2 +iblank,(cy -iheight) * 0. 4,iwidth,iheight); } } void CMfcRibbonTemplateView : :showimage(Mat & src, UINT ID) { if (src.empty()) return; CRect rect; Mat dst = src.clone(); GetDlgItem(ID) - >GetClientRect( &rect ); // 获取控件尺寸位置 if (dst.channels() == 1) cvtColor(dst, dst, CV_GRAY2BGR); resize(dst,dst,Size(rect.Width(),rect.Height())); imshow( "src",dst); } 总体感到jie wu 提出的方法,对于解决比较简单的问题,的确是不错的(我记得halcon生成能够被csharp调用的代码的时候,好像采用的就是类似的方法)。但是它本身存在以下问题: 1、在窗体初始化的时候会有一个黑框弹出来,应该是nameWindow的效果; 2、在没有图片的时候,会自动将Picturebox的背景绘制成为灰色,而且好像不好控制; 3、仅仅是imshow还不能完成全部的调用,比如控件的大小可能还会变化,那么就需要用showimage重新进行封装。 如果加上这些7788的东西,那么最后调用起来,也是比较复杂的。 但是jie wu的方法有一个天生的优点,就是可以调用high gui的callback机制,这个是非常强的东西,能够省不少麻烦事情。 这里只是我粗浅的认识,若有不对之处,欢迎批评指正。 最后说一句,其实看了一些opencv自己的代码,它里面有很多地方就是iplimage和mat相互转换的,很多使用mat接口的函数,只不过是把以前的使用iplimage的函数重新包装了一次。opencv毕竟是一个开源的类库,还有很多地方需要大家一起做得更好。 目前方向:图像拼接融合、图像识别 联系方式:jsxyhelu@foxmail.com

资源下载

更多资源
腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码