报错:“images” contains no shape及解决方案

本文介绍了在TensorFlow中遇到'images' contains no shape错误时,通过添加tf.enable_eager_execution()并重启代码块来解决问题的方法。重点在于如何处理读取文件时shape为空的情况。
部署运行你感兴趣的模型镜像

项目场景:

进行tf 加载数据时,出现“images” contains no shape 错误

问题描述

例如:tf.io.read_file 时,get_shape为空

img = tf.io.read_file(path_to_img)

在这里插入图片描述

解决方案:

在代码开头添加

tf.enable_eager_execution()

restart,重新运行代码块即可。
在这里插入图片描述

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

import torch import torch.nn as nn from utils.trainer import model_init_ from utils.build import check_cfg, build_from_cfg import os import glob from torchvision import transforms, datasets from PIL import Image, ImageDraw, ImageFont import time from graphic.RawDataProcessor import generate_images import imageio import sys import cv2 import numpy as np from torch.utils.data import DataLoader try: from DetModels import YOLOV5S from DetModels.yolo.basic import LoadImages, Profile, Path, non_max_suppression, Annotator, scale_boxes, colorstr, \ Colors, letterbox except ImportError: pass # Current directory and metric directory current_dir = os.path.dirname(os.path.abspath(__file__)) METRIC = os.path.join(current_dir, './metrics') sys.path.append(METRIC) sys.path.append(current_dir) sys.path.append('utils/DetModels/yolo') try: from .metrics.base_metric import EVAMetric except ImportError: pass from logger import colorful_logger # Supported image and raw data extensions image_ext = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff'] raw_data_ext = ['.iq', '.dat'] class Classify_Model(nn.Module): """ A class representing a classification model for performing inference and benchmarking using a pre-trained model. Attributes: - logger (colorful_logger): Logger for logging messages with color. - cfg (str): Path to configuration dictionary. - device (str): Device to use for inference (CPU or GPU). - model (torch.nn.Module): Pre-trained model. - save_path (str): Path to save the results. - save (bool): Flag to indicate whether to save the results. """ def __init__(self, cfg: str = '../configs/exp1_test.yaml', weight_path: str = '../default.path', save: bool = True, ): """ Initializes the Classify_Model. Parameters: - cfg (str): Path to configuration dictionary. - weight_path (str): Path to the pre-trained model weights. - save (bool): Flag to indicate whether to save the results. """ super().__init__() self.logger = self.set_logger if check_cfg(cfg): self.logger.log_with_color(f"Using config file: {cfg}") self.cfg = build_from_cfg(cfg) if self.cfg['device'] == 'cuda': if torch.cuda.is_available(): self.logger.log_with_color("Using GPU for inference") self.device = self.cfg['device'] else: self.logger.log_with_color("Using CPU for inference") self.device = "cpu" if os.path.exists(weight_path): self.logger.log_with_color(f"Using weight file: {weight_path}") self.weight_path = weight_path else: raise FileNotFoundError(f"weight path: {weight_path} does not exist") self.model = self.load_model self.model.to(self.device) self.model.eval() self.save_path = None self.save = save self.confidence_threshold = self.cfg.get('confidence_threshold', 0.49) self.logger.log_with_color(f"Using confidence threshold: {self.confidence_threshold * 100}%") def inference(self, source='../example/', save_path: str = '../result'): """ Performs inference on the given source data. Parameters: - source (str): Path to the source data. - save_path (str): Path to save the results. """ torch.no_grad() if self.save: if not os.path.exists(save_path): os.mkdir(save_path) self.save_path = save_path self.logger.log_with_color(f"Saving results to: {save_path}") if not os.path.exists(source): self.logger.log_with_color(f"Source {source} dose not exit") # dir detect if os.path.isdir(source): data_list = glob.glob(os.path.join(source, '*')) for data in data_list: # detect images in dir if is_valid_file(data, image_ext): self.ImgProcessor(data) # detect raw datas in dir elif is_valid_file(data, raw_data_ext): self.RawdataProcess(data) else: continue # detect single image elif is_valid_file(source, image_ext): self.ImgProcessor(source) # detect single pack of raw data elif is_valid_file(source, raw_data_ext): self.RawdataProcess(source) def forward(self, img): """ Forward pass through the model. Parameters: - img (torch.Tensor): Input image tensor. Returns: - probability (float): Confidence probability of the predicted class. - predicted_class_name (str): Name of the predicted class. """ self.model.eval() temp = self.model(img) probabilities = torch.softmax(temp, dim=1) predicted_class_index = torch.argmax(probabilities, dim=1).item() predicted_class_name = get_key_from_value(self.cfg['class_names'], predicted_class_index) probability = probabilities[0][predicted_class_index].item() * 100 return probability, predicted_class_name @property def load_model(self): """ Loads the pre-trained model. Returns: - model (torch.nn.Module): Loaded model. """ self.logger.log_with_color(f"Using device: {self.device}") # model = model_init_(self.cfg['model'], self.cfg['num_classes'], pretrained=True) model = model_init_(self.cfg['model'], self.cfg['num_classes'], pretrained_path=None) if os.path.exists(self.weight_path): self.logger.log_with_color(f"Loading init weights from: {self.weight_path}") # state_dict = torch.load(self.weight_path, map_location=self.device) state_dict = torch.load(self.weight_path, map_location=self.device, weights_only=True) model.load_state_dict(state_dict) self.logger.log_with_color(f"Successfully loaded pretrained weights from: {self.weight_path}") else: self.logger.log_with_color(f"init weights file not found at: {self.weight_path}. Skipping weight loading.") return model def ImgProcessor(self, source): """ Performs inference on spectromgram data. Parameters: - source (str): Path to the image. """ start_time = time.time() name = os.path.basename(source)[:-4] origin_image = Image.open(source).convert('RGB') preprocessed_image = self.preprocess(source) # 提取文件名(仅保留文件名,不含路径) filename = os.path.basename(source) temp = self.model(preprocessed_image) probabilities = torch.softmax(temp, dim=1) # # 新增:获取最大概率和对应类别索引 max_prob, predicted_class_index = torch.max(probabilities, dim=1) max_prob_val = max_prob.item() # 转换为浮点数' # 核心:计算unknown置信度为1 - 最高置信度(转换为百分比) unknown_prob = (1 - max_prob_val) * 100 # 已知类别置信度为模型输出值(转换为百分比) known_prob = max_prob_val * 100 # predicted_class_index = torch.argmax(probabilities, dim=1).item() # predicted_class_name = get_key_from_value(self.cfg['class_names'], predicted_class_index) if max_prob_val < self.confidence_threshold: predicted_class_name = 'unknown' current_prob = unknown_prob # 使用1-置信度 else: predicted_class_name = get_key_from_value(self.cfg['class_names'], predicted_class_index.item()) current_prob = known_prob # 使用模型原始置信度 end_time = time.time() self.logger.log_with_color(f"Inference time: {(end_time - start_time) / 100 :.8f} sec") # self.logger.log_with_color(f"{source} contains Drone: {predicted_class_name}, " # f"confidence1: {probabilities[0][predicted_class_index].item() * 100 :.2f} %," # f" start saving result") #这个版本是对未知机型置信度做了处理 # self.logger.log_with_color(f"{source} contains Drone: {predicted_class_name}, confidence: {current_prob:.2f}%") # 仅输出:文件名、机型、置信度(简化格式) self.logger.log_with_color(f"{filename}, contains Drone: {predicted_class_name}, {current_prob:.2f}%, 推理时间: {(end_time - start_time):.6f} sec") if self.save: # res = self.add_result(res=predicted_class_name, # probability=probabilities[0][predicted_class_index].item() * 100, # image=origin_image) res = self.add_result(res=predicted_class_name, probability=current_prob, image=origin_image) res.save(os.path.join(self.save_path, name + '.jpg')) def RawdataProcess(self, source): """ Transforming raw data into a video and performing inference on video. Parameters: - source (str): Path to the raw data. """ res = [] images = generate_images(source) name = os.path.splitext(os.path.basename(source)) for image in images: temp = self.model(self.preprocess(image)) probabilities = torch.softmax(temp, dim=1) predicted_class_index = torch.argmax(probabilities, dim=1).item() predicted_class_name = get_key_from_value(self.cfg['class_names'], predicted_class_index) _ = self.add_result(res=predicted_class_name, probability=probabilities[0][predicted_class_index].item() * 100, image=image) res.append(_) imageio.mimsave(os.path.join(self.save_path, name + '.mp4'), res, fps=5) def add_result(self, res, image, position=(40, 40), font="arial.ttf", font_size=45, text_color=(255, 0, 0), probability=0.0 ): """ Adds the inference result to the image. Parameters: - res (str): Inference result. - image (PIL.Image): Input image. - position (tuple): Position to add the text. - font (str): Font file path. - font_size (int): Font size. - text_color (tuple): Text color. - probability (float): Confidence probability. Returns: - image (PIL.Image): Image with added result. """ draw = ImageDraw.Draw(image) font = ImageFont.truetype("C:/Windows/Fonts/simhei.ttf", font_size) draw.text(position, res + f" {probability:.2f}%", fill=text_color, font=font) return image @property def set_logger(self): """ Sets up the logger. Returns: - logger (colorful_logger): Logger instance. """ logger = colorful_logger('Inference') return logger def preprocess(self, img): transform = transforms.Compose([ transforms.Resize((self.cfg['image_size'], self.cfg['image_size'])), transforms.ToTensor(), ]) image = Image.open(img).convert('RGB') preprocessed_image = transform(image) preprocessed_image = preprocessed_image.to(self.device) preprocessed_image = preprocessed_image.unsqueeze(0) return preprocessed_image def benchmark(self, data_path, save_path=None): """ Performs benchmarking on the given data and calculates evaluation metrics. Parameters: - data_path (str): Path to the benchmark data. Returns: - metrics (dict): Dictionary containing evaluation metrics. """ snrs = os.listdir(data_path) if not save_path: save_path = os.path.join(data_path, 'benchmark result') if not os.path.exists(save_path): os.mkdir(save_path) if not os.path.exists(save_path): os.mkdir(save_path) #根据得到映射关系写下面的,我得到的是★ 最佳映射 pred → gt: {0: 2, 1: 1, 2: 3, 3: 4, 4: 0} #MAP_P2G=torch.tensor([2,1,3,4,0],device=self.cfg['device']) #INV_MAP=torch.argsort(MAP_P2G) with torch.no_grad(): for snr in snrs: CMS = os.listdir(os.path.join(data_path, snr)) for CM in CMS: stat_time = time.time() self.model.eval() _dataset = datasets.ImageFolder( root=os.path.join(data_path, snr, CM), transform=transforms.Compose([ transforms.Resize((self.cfg['image_size'], self.cfg['image_size'])), transforms.ToTensor(),]) ) dataset = DataLoader(_dataset, batch_size=self.cfg['batch_size'], shuffle=self.cfg['shuffle']) print("Starting Benchmark...") correct = 0 total = 0 probabilities = [] total_labels = [] classes_name = tuple(self.cfg['class_names'].keys()) cm_raw = np.zeros((5, 5), dtype=int) for images, labels in dataset: images, labels = images.to(self.cfg['device']), labels.to(self.cfg['device']) outputs = self.model(images) #outputs=outputs[:,INV_MAP] #probs =torch.softmax(outputs,dim=1) for output in outputs: probabilities.append(list(torch.softmax(output, dim=0))) _, predicted = outputs.max(1) for p, t in zip(predicted.cpu(), labels.cpu()): cm_raw[p,t]+=1 cm_raw[p, t] += 1 # 行 = pred, 列 = gt total += labels.size(0) correct += predicted.eq(labels).sum().item() total_labels.append(labels) _total_labels = torch.concat(total_labels, dim=0) _probabilities = torch.tensor(probabilities) metrics = EVAMetric(preds=_probabilities.to(self.cfg['device']), labels=_total_labels, num_classes=self.cfg['num_classes'], tasks=('f1', 'precision', 'CM'), topk=(1, 3, 5), save_path=save_path, classes_name=classes_name, pic_name=f'{snr}_{CM}') metrics['acc'] = 100 * correct / total s = (f'{snr} ' + f'CM: {CM} eva result:' + ' acc: ' + f'{metrics["acc"]}' + ' top-1: ' + f'{metrics["Top-k"]["top1"]}' + ' top-1: ' + f'{metrics["Top-k"]["top1"]}' + ' top-2 ' + f'{metrics["Top-k"]["top2"]}' + ' top-3 ' + f'{metrics["Top-k"]["top3"]}' + ' mAP: ' + f'{metrics["mAP"]["mAP"]}' + ' macro_f1: ' + f'{metrics["f1"]["macro_f1"]}' + ' micro_f1 : ' + f' {metrics["f1"]["micro_f1"]}\n') txt_path = os.path.join(save_path, 'benchmark_result.txt') colorful_logger(f'cost {(time.time()-stat_time)/60} mins') with open(txt_path, 'a') as file: file.write(s) print(f'{CM} Done!') print(f'{snr} Done!') row_ind, col_ind = linear_sum_assignment(-cm_raw) # 取负→最大化对角线 mapping_pred2gt = {int(r): int(c) for r, c in zip(row_ind, col_ind)} print("\n★ 最佳映射 pred → gt:", mapping_pred2gt) # 若要保存下来以后用: import json json.dump(mapping_pred2gt, open('class_to_idx_pred2gt.json', 'w')) print("映射已保存到 class_to_idx_pred2gt.json") class Detection_Model: """ A common interface for initializing and running different detection models. This class provides methods to initialize and run object detection models such as YOLOv5 and Faster R-CNN. It allows for easy switching between different models by providing a unified interface. Attributes: - S1model: The initialized detection model (e.g., YOLOv5S). - model_name: The name of the detection model to be used. - weight_path: The path to the pre-trained model weights. Methods: - __init__(self, cfg=None, model_name=None, weight_path=None): Initializes the detection model based on the provided configuration or parameters. If a configuration dictionary `cfg` is provided, it will be used to set the model name and weight path. Otherwise, the `model_name` and `weight_path` parameters can be specified directly. - yolov5_detect(self, source='../example/source/', save_dir='../res', imgsz=(640, 640), conf_thres=0.6, iou_thres=0.45, max_det=1000, line_thickness=3, hide_labels=True, hide_conf=False): Runs YOLOv5 object detection on the specified source. - source: Path to the input image or directory containing images. - save_dir: Directory to save the detection results. - imgsz: Image size for inference (height, width). - conf_thres: Confidence threshold for filtering detections. - iou_thres: IoU threshold for non-maximum suppression. - max_det: Maximum number of detections per image. - line_thickness: Thickness of the bounding box lines. - hide_labels: Whether to hide class labels in the output. - hide_conf: Whether to hide confidence scores in the output. - faster_rcnn_detect(self, source='../example/source/', save_dir='../res', weight_path='../example/detect/', imgsz=(640, 640), conf_thres=0.25, iou_thres=0.45, max_det=1000, line_thickness=3, hide_labels=False, hide_conf=False): Placeholder method for running Faster R-CNN object detection. This method is currently not implemented and should be replaced with the actual implementation. """ def __init__(self, cfg=None, model_name=None, weight_path=None): if cfg: model_name = cfg['model_name'] weight_path = cfg['weight_path'] if model_name == 'yolov5': self.S1model = YOLOV5S(weights=weight_path) self.S1model.inference = self.yolov5_detect # ToDo elif model_name == 'faster_rcnn': self.S1model = YOLOV5S(weights=weight_path) self.S1model.inference = self.yolov5_detect else: if model_name == 'yolov5': self.S1model = YOLOV5S(weights=weight_path) self.S1model.inference = self.yolov5_detect # ToDo elif model_name == 'faster_rcnn': self.S1model = YOLOV5S(weights=weight_path) self.S1model.inference = self.yolov5_detect def yolov5_detect(self, source='../example/source/', save_dir='../res', imgsz=(640, 640), conf_thres=0.6, iou_thres=0.45, max_det=1000, line_thickness=3, hide_labels=True, hide_conf=False, ): color = Colors() detmodel = self.S1model stride, names = detmodel.stride, detmodel.names torch.no_grad() # Run inference if isinstance(source, np.ndarray): detmodel.eval() im = letterbox(source, imgsz, stride=stride, auto=True)[0] # padded resize im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB im = np.ascontiguousarray(im) # contiguous im = torch.from_numpy(im).to(detmodel.device) im = im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim # Inference pred = detmodel(im) # NMS pred = non_max_suppression(pred, conf_thres, iou_thres, agnostic=False, max_det=max_det) # Process predictions for i, det in enumerate(pred): # per image annotator = Annotator(source, line_width=line_thickness, example=str(names)) if len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], source.shape).round() # Print results for c in det[:, 5].unique(): n = (det[:, 5] == c).sum() # detections per class for *xyxy, conf, cls in reversed(det): c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') annotator.box_label(xyxy, label, color=color(c + 2, True)) # Stream results im0 = annotator.result() # Save results (image with detections) return im0 else: # Ensure the save directory exists os.makedirs(save_dir, exist_ok=True) dataset = LoadImages(source, img_size=imgsz, stride=stride) seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) for path, im, im0s, s in dataset: im = torch.from_numpy(im).to(detmodel.device) im = im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim # Inference pred = detmodel(im) # NMS pred = non_max_suppression(pred, conf_thres, iou_thres, agnostic=False, max_det=max_det) # Process predictions for i, det in enumerate(pred): # per image seen += 1 p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0) p = Path(p) # to Path save_path = str(save_dir + p.name) # im.jpg s += '%gx%g ' % im.shape[2:] # print string annotator = Annotator(im0, line_width=line_thickness, example=str(names)) if len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, 5].unique(): n = (det[:, 5] == c).sum() # detections per class s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string for *xyxy, conf, cls in reversed(det): c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') annotator.box_label(xyxy, label, color=color(c + 2, True)) # Stream results im0 = annotator.result() # Save results (image with detections) if save_dir == 'buffer': return im0 else: cv2.imwrite(save_path, im0) del im0 # Release memory after saving # Print results print(f"Results saved to {colorstr('bold', save_dir)}") #ToDo def faster_rcnn_detect(self, source='../example/source/', save_dir='../res', weight_path='../example/detect/', imgsz=(640, 640), conf_thres=0.25, iou_thres=0.45, max_det=1000, line_thickness=3, hide_labels=False, hide_conf=False, ): pass def is_valid_file(path, total_ext): """ Checks if the file has a valid extension. Parameters: - path (str): Path to the file. - total_ext (list): List of valid extensions. Returns: - bool: True if the file has a valid extension, False otherwise. """ last_element = os.path.basename(path) if any(last_element.lower().endswith(ext) for ext in total_ext): return True else: return False def get_key_from_value(d, value): """ Gets the key from a dictionary based on the value. Parameters: - d (dict): Dictionary. - value: Value to find the key for. Returns: - key: Key corresponding to the value, or None if not found. """ for key, val in d.items(): if val == value: return key return None def preprocess_image_yolo(im0, imgsz, stride, detmodel): im = letterbox(im0, imgsz, stride=stride, auto=True)[0] # padded resize im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB im = np.ascontiguousarray(im) # contiguous im = torch.from_numpy(im).to(detmodel.device) im = im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim return im def process_predictions_yolo(det, im, im0, names, line_thickness, hide_labels, hide_conf, color): annotator = Annotator(im0, line_width=line_thickness, example=str(names)) if len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, 5].unique(): n = (det[:, 5] == c).sum() # detections per class for *xyxy, conf, cls in reversed(det): c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') annotator.box_label(xyxy, label, color=color(c + 2, True)) # Stream results im0 = annotator.result() return im0 # Usage----------------------------------------------------------------------------------------------------------------- def main(): """ cfg = '' weight_path = '' source = '' save_path = '' test = Classify_Model(cfg=cfg, weight_path=weight_path) test.inference(source=source, save_path=save_path) # test.benchmark() """ """ source = '' weight_path = '' save_dir = '' test = Detection_Model(model_name='yolov5', weight_path=weight_path) test.yolov5_detect(source=source, save_dir=save_dir,) """ if __name__ == '__main__': main() 报错部分代码是这样的,我该怎么做,才能让我的推理正常跑通呢
09-08
# Ultralytics YOLO 🚀, AGPL-3.0 license import json import random from collections import defaultdict from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path import cv2 import numpy as np import torch from PIL import Image from torch.utils.data import ConcatDataset from ultralytics.utils import LOCAL_RANK, NUM_THREADS, TQDM, colorstr from ultralytics.utils.ops import resample_segments from ultralytics.utils.torch_utils import TORCHVISION_0_18 from .augment import ( Compose, Format, LetterBox, RandomLoadText, classify_augmentations, classify_transforms, v8_transforms, ) from .base import BaseDataset from .utils import ( HELP_URL, LOGGER, get_hash, img2label_paths, load_dataset_cache_file, save_dataset_cache_file, verify_image, verify_image_label, ) # Ultralytics dataset *.cache version, >= 1.0.0 for YOLOv8 DATASET_CACHE_VERSION = "1.0.3" # 修复点1: 添加完整的Instances类定义(包含convert_bbox和denormalize方法) class Instances: """Instances class for handling bounding boxes, segments, and keypoints in object detection.""" def __init__(self, bboxes, segments=None, keypoints=None, bbox_format="xywh", normalized=True): """ Initialize Instances. Args: bboxes (np.ndarray): Bounding boxes array segments (np.ndarray, optional): Segmentation masks keypoints (np.ndarray, optional): Keypoints bbox_format (str): Bounding box format ('xywh', 'xyxy', etc.) normalized (bool): Whether coordinates are normalized """ self.bboxes = bboxes self.segments = segments self.keypoints = keypoints self.bbox_format = bbox_format self.normalized = normalized self.cls = None # 添加cls属性占位 def __len__(self): """Return the number of instances.""" return len(self.bboxes) @classmethod def empty(cls): """Return an empty Instances object.""" return cls(np.zeros((0, 4), dtype=np.float32)) @classmethod def cat(cls, instances_list): """Concatenate multiple Instances objects into one.""" bboxes = np.concatenate([inst.bboxes for inst in instances_list], axis=0) segments = np.concatenate([inst.segments for inst in instances_list], axis=0) if instances_list[0].segments is not None else None keypoints = np.concatenate([inst.keypoints for inst in instances_list], axis=0) if instances_list[0].keypoints is not None else None return cls(bboxes, segments, keypoints, bbox_format=instances_list[0].bbox_format, normalized=instances_list[0].normalized) def convert_bbox(self, format): """Convert bounding box format. Args: format (str): Target format, either 'xyxy' or 'xywh'. """ if self.bbox_format == format: return if self.bbox_format == "xywh" and format == "xyxy": # Convert from xywh to xyxy x, y, w, h = self.bboxes.T xyxy = np.array([x - w/2, y - h/2, x + w/2, y + h/2]).T self.bboxes = xyxy self.bbox_format = "xyxy" elif self.bbox_format == "xyxy" and format == "xywh": # Convert from xyxy to xywh x1, y1, x2, y2 = self.bboxes.T xywh = np.array([(x1+x2)/2, (y1+y2)/2, x2-x1, y2-y1]).T self.bboxes = xywh self.bbox_format = "xywh" else: raise ValueError(f"Conversion from {self.bbox_format} to {format} not supported") # 添加缺失的denormalize方法 def denormalize(self, w, h): """ Denormalize bounding boxes from normalized coordinates to pixel coordinates. Args: w (int): Image width h (int): Image height """ if not self.normalized: return if self.bboxes is not None and len(self.bboxes) > 0: if self.bbox_format == "xywh": # Denormalize xywh format self.bboxes[:, 0] *= w self.bboxes[:, 1] *= h self.bboxes[:, 2] *= w self.bboxes[:, 3] *= h elif self.bbox_format == "xyxy": # Denormalize xyxy format self.bboxes[:, [0, 2]] *= w self.bboxes[:, [1, 3]] *= h # 处理segments(如果存在) if self.segments is not None and len(self.segments) > 0: # segments shape: (n, num_points, 2) self.segments[..., 0] *= w self.segments[..., 1] *= h # 处理keypoints(如果存在) if self.keypoints is not None and len(self.keypoints) > 0: # keypoints shape: (n, num_keypoints, 2 or 3) self.keypoints[..., 0] *= w self.keypoints[..., 1] *= h self.normalized = False class Mosaic: """Mosaic data augmentation for object detection datasets. This class combines 4 images into a single mosaic image, adjusting labels accordingly. """ def __init__(self, dataset, imgsz=640, p=0.5, border=[-320, -320]): """ Initialize Mosaic augmentation. Args: dataset (YOLODataset): The dataset object imgsz (int): Output image size (height and width) p (float): Probability of applying mosaic augmentation border (list): Border values for random center placement """ self.dataset = dataset self.imgsz = imgsz self.p = p self.border = border self.mosaic_border = [-imgsz // 2, -imgsz // 2] def __call__(self, data): """Apply mosaic augmentation to a batch of data.""" # Only apply mosaic with given probability if random.random() > self.p: return data # Check if data contains necessary components if 'img' not in data or 'instances' not in data: return data # Get current image and instances img = data['img'] instances = data['instances'] h0, w0 = img.shape[:2] # original height and width # Create mosaic image mosaic_img = np.full((self.imgsz * 2, self.imgsz * 2, img.shape[2]), 114, dtype=np.uint8) # Random center placement yc, xc = [int(random.uniform(-x, 2 * self.imgsz + x)) for x in self.mosaic_border] # Get 3 additional random indices indices = [random.randint(0, len(self.dataset) - 1) for _ in range(3)] mosaic_instances = [] # Place 4 images in mosaic for i, index in enumerate([0] + indices): if i == 0: # current image img_i, instances_i = img, instances else: # Get other image and instances from dataset data_i = self.dataset[index] img_i = data_i['img'] instances_i = data_i['instances'] # Resize image r = self.imgsz / max(img_i.shape[:2]) img_i = cv2.resize(img_i, (int(w0 * r), int(h0 * r)), interpolation=cv2.INTER_LINEAR) h, w = img_i.shape[:2] # Place image in mosaic if i == 0: # top left x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, self.imgsz * 2), yc x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(self.imgsz * 2, yc + h) x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(h, y2a - y1a) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc + w, self.imgsz * 2), min(self.imgsz * 2, yc + h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(h, y2a - y1a) # Place image segment in mosaic mosaic_img[y1a:y2a, x1a:x2a] = img_i[y1b:y2b, x1b:x2b] padw, padh = x1a - x1b, y1a - y1b # Adjust instances if they exist if instances_i is not None and len(instances_i) > 0: # 确保使用xyxy格式进行处理 if instances_i.bbox_format != "xyxy": instances_i.convert_bbox("xyxy") # 修复点2: 使用copy()代替clone()处理NumPy数组 bboxes_copy = instances_i.bboxes.copy() segments_copy = instances_i.segments.copy() if instances_i.segments is not None else None keypoints_copy = instances_i.keypoints.copy() if instances_i.keypoints is not None else None # Create a copy of instances to avoid modifying original new_instances = Instances( bboxes_copy, segments_copy, keypoints_copy, bbox_format=instances_i.bbox_format, normalized=instances_i.normalized ) # Adjust bboxes if new_instances.bboxes is not None and len(new_instances.bboxes) > 0: bboxes = new_instances.bboxes if new_instances.normalized: # Convert normalized coordinates to pixels bboxes[:, [0, 2]] = bboxes[:, [0, 2]] * w bboxes[:, [1, 3]] = bboxes[:, [1, 3]] * h # Adjust coordinates bboxes[:, [0, 2]] = bboxes[:, [0, 2]] * r + padw bboxes[:, [1, 3]] = bboxes[:, [1, 3]] * r + padh # Convert back to normalized coordinates bboxes[:, [0, 2]] = bboxes[:, [0, 2]] / (self.imgsz * 2) bboxes[:, [1, 3]] = bboxes[:, [1, 3]] / (self.imgsz * 2) # Filter boxes that are completely outside the mosaic valid = ( (bboxes[:, 0] < 1) & (bboxes[:, 1] < 1) & (bboxes[:, 2] > 0) & (bboxes[:, 3] > 0)) new_instances.bboxes = bboxes[valid] # Adjust class labels if present if new_instances.cls is not None: new_instances.cls = new_instances.cls[valid] # Add adjusted instances to mosaic mosaic_instances.append(new_instances) # Combine all instances if mosaic_instances: updated_instances = Instances.cat(mosaic_instances) else: updated_instances = Instances.empty() # Update data dictionary data['img'] = mosaic_img data['instances'] = updated_instances data['mosaic_border'] = self.mosaic_border return data class YOLODataset(BaseDataset): """ Dataset class for loading object detection and/or segmentation labels in YOLO format. Args: data (dict, optional): A dataset YAML dictionary. Defaults to None. task (str): An explicit arg to point current task, Defaults to 'detect'. Returns: (torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model. """ def __init__(self, *args, data=None, task="detect", **kwargs): """Initializes the YOLODataset with optional configurations for segments and keypoints.""" self.use_segments = task == "segment" self.use_keypoints = task == "pose" self.use_obb = task == "obb" self.data = data self.mosaic_enabled = False # Will be enabled in build_transforms if conditions met assert not (self.use_segments and self.use_keypoints), "Can not use both segments and keypoints." super().__init__(*args, **kwargs) def cache_labels(self, path=Path("./labels.cache")): """ Cache dataset labels, check images and read shapes. Args: path (Path): Path where to save the cache file. Default is Path('./labels.cache'). Returns: (dict): labels. """ x = {"labels": []} nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages desc = f"{self.prefix}Scanning {path.parent / path.stem}..." total = len(self.im_files) nkpt, ndim = self.data.get("kpt_shape", (0, 0)) if self.use_keypoints and (nkpt <= 0 or ndim not in {2, 3}): raise ValueError( "'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of " "keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'" ) with ThreadPool(NUM_THREADS) as pool: results = pool.imap( func=verify_image_label, iterable=zip( self.im_files, self.label_files, repeat(self.prefix), repeat(self.use_keypoints), repeat(len(self.data["names"])), repeat(nkpt), repeat(ndim), ), ) pbar = TQDM(results, desc=desc, total=total) for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar: nm += nm_f nf += nf_f ne += ne_f nc += nc_f if im_file: x["labels"].append( { "im_file": im_file, "shape": shape, "cls": lb[:, 0:1], # n, 1 "bboxes": lb[:, 1:], # n, 4 "segments": segments, "keypoints": keypoint, "normalized": True, "bbox_format": "xywh", } ) if msg: msgs.append(msg) pbar.desc = f"{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt" pbar.close() if msgs: LOGGER.info("\n".join(msgs)) if nf == 0: LOGGER.warning(f"{self.prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}") x["hash"] = get_hash(self.label_files + self.im_files) x["results"] = nf, nm, ne, nc, len(self.im_files) x["msgs"] = msgs # warnings save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION) return x def get_labels(self): """Returns dictionary of labels for YOLO training.""" self.label_files = img2label_paths(self.im_files) cache_path = Path(self.label_files[0]).parent.with_suffix(".cache") try: cache, exists = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file assert cache["version"] == DATASET_CACHE_VERSION # matches current version assert cache["hash"] == get_hash(self.label_files + self.im_files) # identical hash except (FileNotFoundError, AssertionError, AttributeError): cache, exists = self.cache_labels(cache_path), False # run cache ops # Display cache nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total if exists and LOCAL_RANK in {-1, 0}: d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt" TQDM(None, desc=self.prefix + d, total=n, initial=n) # display results if cache["msgs"]: LOGGER.info("\n".join(cache["msgs"])) # display warnings # Read cache [cache.pop(k) for k in ("hash", "version", "msgs")] # remove items labels = cache["labels"] if not labels: LOGGER.warning(f"WARNING ⚠️ No images found in {cache_path}, training may not work correctly. {HELP_URL}") self.im_files = [lb["im_file"] for lb in labels] # update im_files # Check if the dataset is all boxes or all segments lengths = ((len(lb["cls"]), len(lb["bboxes"]), len(lb["segments"])) for lb in labels) len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths)) if len_segments and len_boxes != len_segments: LOGGER.warning( f"WARNING ⚠️ Box and segment counts should be equal, but got len(segments) = {len_segments}, " f"len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. " "To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset." ) for lb in labels: lb["segments"] = [] if len_cls == 0: LOGGER.warning(f"WARNING ⚠️ No labels found in {cache_path}, training may not work correctly. {HELP_URL}") return labels def build_transforms(self, hyp=None): """Builds and appends transforms to the list.""" if self.augment: # Enable mosaic if specified in hyperparameters self.mosaic_enabled = hyp.mosaic > 0 if self.augment and not self.rect else False hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0 hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0 # Create transforms list transforms = [] # Add Mosaic transform if enabled if self.mosaic_enabled: transforms.append(Mosaic(self, self.imgsz, p=hyp.mosaic)) # Add other standard transforms transforms.extend(v8_transforms(self, self.imgsz, hyp)) else: transforms = [Compose(LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False))] # Add format transform transforms.append( Format( bbox_format="xywh", normalize=True, return_mask=self.use_segments, return_keypoint=self.use_keypoints, return_obb=self.use_obb, batch_idx=True, mask_ratio=hyp.mask_ratio, mask_overlap=hyp.overlap_mask, bgr=hyp.bgr if self.augment else 0.0, # only affect training. ) ) # Return as Compose object return Compose(transforms) def close_mosaic(self, hyp): """Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.""" hyp.mosaic = 0.0 # set mosaic ratio=0.0 hyp.copy_paste = 0.0 # keep the same behavior as previous v8 close-mosaic hyp.mixup = 0.0 # keep the same behavior as previous v8 close-mosaic self.transforms = self.build_transforms(hyp) def update_labels_info(self, label): """ Custom your label format here. Note: cls is not with bboxes now, classification and semantic segmentation need an independent cls label Can also support classification and semantic segmentation by adding or removing dict keys there. """ bboxes = label.pop("bboxes") segments = label.pop("segments", []) keypoints = label.pop("keypoints", None) bbox_format = label.pop("bbox_format") normalized = label.pop("normalized") # NOTE: do NOT resample oriented boxes segment_resamples = 100 if self.use_obb else 1000 if len(segments) > 0: # list[np.array(1000, 2)] * num_samples # (N, 1000, 2) segments = np.stack(resample_segments(segments, n=segment_resamples), axis=0) else: segments = np.zeros((0, segment_resamples, 2), dtype=np.float32) label["instances"] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized) return label @staticmethod def collate_fn(batch): """Collates data samples into batches.""" new_batch = {} keys = batch[0].keys() values = list(zip(*[list(b.values()) for b in batch])) for i, k in enumerate(keys): value = values[i] if k == "img": value = torch.stack(value, 0) if k in {"masks", "keypoints", "bboxes", "cls", "segments", "obb"}: value = torch.cat(value, 0) new_batch[k] = value new_batch["batch_idx"] = list(new_batch["batch_idx"]) for i in range(len(new_batch["batch_idx"])): new_batch["batch_idx"][i] += i # add target image index for build_targets() new_batch["batch_idx"] = torch.cat(new_batch["batch_idx"], 0) return new_batch class YOLOMultiModalDataset(YOLODataset): """ Dataset class for loading object detection and/or segmentation labels in YOLO format. Args: data (dict, optional): A dataset YAML dictionary. Defaults to None. task (str): An explicit arg to point current task, Defaults to 'detect'. Returns: (torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model. """ def __init__(self, *args, data=None, task="detect", **kwargs): """Initializes a dataset object for object detection tasks with optional specifications.""" super().__init__(*args, data=data, task=task, **kwargs) def update_labels_info(self, label): """Add texts information for multi-modal model training.""" labels = super().update_labels_info(label) # NOTE: some categories are concatenated with its synonyms by `/`. labels["texts"] = [v.split("/") for _, v in self.data["names"].items()] return labels def build_transforms(self, hyp=None): """Enhances data transformations with optional text augmentation for multi-modal training.""" transforms = super().build_transforms(hyp) if self.augment: # NOTE: hard-coded the args for now. transforms.insert(-1, RandomLoadText(max_samples=min(self.data["nc"], 80), padding=True)) return transforms class GroundingDataset(YOLODataset): """Handles object detection tasks by loading annotations from a specified JSON file, supporting YOLO format.""" def __init__(self, *args, task="detect", json_file, **kwargs): """Initializes a GroundingDataset for object detection, loading annotations from a specified JSON file.""" assert task == "detect", "`GroundingDataset` only support `detect` task for now!" self.json_file = json_file super().__init__(*args, task=task, data={}, **kwargs) def get_img_files(self, img_path): """The image files would be read in `get_labels` function, return empty list here.""" return [] def get_labels(self): """Loads annotations from a JSON file, filters, and normalizes bounding boxes for each image.""" labels = [] LOGGER.info("Loading annotation file...") with open(self.json_file) as f: annotations = json.load(f) images = {f'{x["id"]:d}': x for x in annotations["images"]} img_to_anns = defaultdict(list) for ann in annotations["annotations"]: img_to_anns[ann["image_id"]].append(ann) for img_id, anns in TQDM(img_to_anns.items(), desc=f"Reading annotations {self.json_file}"): img = images[f"{img_id:d}"] h, w, f = img["height"], img["width"], img["file_name"] im_file = Path(self.img_path) / f if not im_file.exists(): continue self.im_files.append(str(im_file)) bboxes = [] cat2id = {} texts = [] for ann in anns: if ann["iscrowd"]: continue box = np.array(ann["bbox"], dtype=np.float32) box[:2] += box[2:] / 2 box[[0, 2]] /= float(w) box[[1, 3]] /= float(h) if box[2] <= 0 or box[3] <= 0: continue cat_name = " ".join([img["caption"][t[0] : t[1]] for t in ann["tokens_positive"]]) if cat_name not in cat2id: cat2id[cat_name] = len(cat2id) texts.append([cat_name]) cls = cat2id[cat_name] # class box = [cls] + box.tolist() if box not in bboxes: bboxes.append(box) lb = np.array(bboxes, dtype=np.float32) if len(bboxes) else np.zeros((0, 5), dtype=np.float32) labels.append( { "im_file": im_file, "shape": (h, w), "cls": lb[:, 0:1], # n, 1 "bboxes": lb[:, 1:], # n, 4 "normalized": True, "bbox_format": "xywh", "texts": texts, } ) return labels def build_transforms(self, hyp=None): """Configures augmentations for training with optional text loading; `hyp` adjusts augmentation intensity.""" transforms = super().build_transforms(hyp) if self.augment: # NOTE: hard-coded the args for now. transforms.insert(-1, RandomLoadText(max_samples=80, padding=True)) return transforms class YOLOConcatDataset(ConcatDataset): """ Dataset as a concatenation of multiple datasets. This class is useful to assemble different existing datasets. """ @staticmethod def collate_fn(batch): """Collates data samples into batches.""" return YOLODataset.collate_fn(batch) # TODO: support semantic segmentation class SemanticDataset(BaseDataset): """ Semantic Segmentation Dataset. This class is responsible for handling datasets used for semantic segmentation tasks. It inherits functionalities from the BaseDataset class. Note: This class is currently a placeholder and needs to be populated with methods and attributes for supporting semantic segmentation tasks. """ def __init__(self): """Initialize a SemanticDataset object.""" super().__init__() class ClassificationDataset: """ Extends torchvision ImageFolder to support YOLO classification tasks, offering functionalities like image augmentation, caching, and verification. It's designed to efficiently handle large datasets for training deep learning models, with optional image transformations and caching mechanisms to speed up training. This class allows for augmentations using both torchvision and Albumentations libraries, and supports caching images in RAM or on disk to reduce IO overhead during training. Additionally, it implements a robust verification process to ensure data integrity and consistency. Attributes: cache_ram (bool): Indicates if caching in RAM is enabled. cache_disk (bool): Indicates if caching on disk is enabled. samples (list): A list of tuples, each containing the path to an image, its class index, path to its .npy cache file (if caching on disk), and optionally the loaded image array (if caching in RAM). torch_transforms (callable): PyTorch transforms to be applied to the images. """ def __init__(self, root, args, augment=False, prefix=""): """ Initialize YOLO object with root, image size, augmentations, and cache settings. Args: root (str): Path to the dataset directory where images are stored in a class-specific folder structure. args (Namespace): Configuration containing dataset-related settings such as image size, augmentation parameters, and cache settings. It includes attributes like `imgsz` (image size), `fraction` (fraction of data to use), `scale`, `fliplr`, `flipud`, `cache` (disk or RAM caching for faster training), `auto_augment`, `hsv_h`, `hsv_s`, `hsv_v`, and `crop_fraction`. augment (bool, optional): Whether to apply augmentations to the dataset. Default is False. prefix (str, optional): Prefix for logging and cache filenames, aiding in dataset identification and debugging. Default is an empty string. """ import torchvision # scope for faster 'import ultralytics' # Base class assigned as attribute rather than used as base class to allow for scoping slow torchvision import if TORCHVISION_0_18: # 'allow_empty' argument first introduced in torchvision 0.18 self.base = torchvision.datasets.ImageFolder(root=root, allow_empty=True) else: self.base = torchvision.datasets.ImageFolder(root=root) self.samples = self.base.samples self.root = self.base.root # Initialize attributes if augment and args.fraction < 1.0: # reduce training fraction self.samples = self.samples[: round(len(self.samples) * args.fraction)] self.prefix = colorstr(f"{prefix}: ") if prefix else "" self.cache_ram = args.cache is True or str(args.cache).lower() == "ram" # cache images into RAM if self.cache_ram: LOGGER.warning( "WARNING ⚠️ Classification `cache_ram` training has known memory leak in " "https://github.com/ultralytics/ultralytics/issues/9824, setting `cache_ram=False`." ) self.cache_ram = False self.cache_disk = str(args.cache).lower() == "disk" # cache images on hard drive as uncompressed *.npy files self.samples = self.verify_images() # filter out bad images self.samples = [list(x) + [Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im scale = (1.0 - args.scale, 1.0) # (0.08, 1.0) self.torch_transforms = ( classify_augmentations( size=args.imgsz, scale=scale, hflip=args.fliplr, vflip=args.flipud, erasing=args.erasing, auto_augment=args.auto_augment, hsv_h=args.hsv_h, hsv_s=args.hsv_s, hsv_v=args.hsv_v, ) if augment else classify_transforms(size=args.imgsz, crop_fraction=args.crop_fraction) ) def __getitem__(self, i): """Returns subset of data and targets corresponding to given indices.""" f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image if self.cache_ram: if im is None: # Warning: two separate if statements required here, do not combine this with previous line im = self.samples[i][3] = cv2.imread(f) elif self.cache_disk: if not fn.exists(): # load npy np.save(fn.as_posix(), cv2.imread(f), allow_pickle=False) im = np.load(fn) else: # read image im = cv2.imread(f) # BGR # Convert NumPy array to PIL image im = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)) sample = self.torch_transforms(im) return {"img": sample, "cls": j} def __len__(self) -> int: """Return the total number of samples in the dataset.""" return len(self.samples) def verify_images(self): """Verify all images in dataset.""" desc = f"{self.prefix}Scanning {self.root}..." path = Path(self.root).with_suffix(".cache") # *.cache file path try: cache = load_dataset_cache_file(path) # attempt to load a *.cache file assert cache["version"] == DATASET_CACHE_VERSION # matches current version assert cache["hash"] == get_hash([x[0] for x in self.samples]) # identical hash nf, nc, n, samples = cache.pop("results") # found, missing, empty, corrupt, total if LOCAL_RANK in {-1, 0}: d = f"{desc} {nf} images, {nc} corrupt" TQDM(None, desc=d, total=n, initial=n) if cache["msgs"]: LOGGER.info("\n".join(cache["msgs"])) # display warnings return samples except (FileNotFoundError, AssertionError, AttributeError): # Run scan if *.cache retrieval failed nf, nc, msgs, samples, x = 0, 0, [], [], {} with ThreadPool(NUM_THREADS) as pool: results = pool.imap(func=verify_image, iterable=zip(self.samples, repeat(self.prefix))) pbar = TQDM(results, desc=desc, total=len(self.samples)) for sample, nf_f, nc_f, msg in pbar: if nf_f: samples.append(sample) if msg: msgs.append(msg) nf += nf_f nc += nc_f pbar.desc = f"{desc} {nf} images, {nc} corrupt" pbar.close() if msgs: LOGGER.info("\n".join(msgs)) x["hash"] = get_hash([x[0] for x in self.samples]) x["results"] = nf, nc, len(samples), samples x["msgs"] = msgs # warnings save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION) return samples(这是dataset.py代码)
最新发布
09-25
### Python 中 `ModuleNotFoundError: No module named 'frontend'` 的解决方案 当在 Python 环境中遇到 `ModuleNotFoundError: No module named 'frontend'` 错误时,通常是因为某些模块未正确安装或导入路径存在问题。以下是详细的分析和解决方法: #### 1. **确认模块是否存在** 首先需要验证是否有名为 `frontend` 的模块被显式定义或作为第三方库的一部分存在。如果没有这样的模块,则可能是某个依赖项的内部实现问题。 如果问题是由于使用了 `fitz` 或者 `PyMuPDF` 库引起的,那么可能的原因是这些库在其初始化过程中尝试从不存在的子模块加载资源[^2]。 #### 2. **卸载并重新安装相关库** 对于由 `fitz` 引发的问题,建议按照以下步骤操作: - 卸载当前版本的 `fitz`: ```bash pip uninstall fitz ``` - 安装经过测试稳定的 `PyMuPDF` 版本(例如 v1.24.1): ```bash pip install PyMuPDF==1.24.1 ``` 使用特定版本号可以规避潜在兼容性问题[^2]。 #### 3. **调整模块导入语句** 若仍然出现类似错误,检查涉及的脚本是否通过不恰当的方式引用了缺失模块。例如,在某些情况下,将 `from frontend import *` 替换为更具体的相对路径形式如 `from fitz.frontend import *` 可能解决问题[^3]。 #### 4. **环境隔离与依赖管理** 推荐创建独立虚拟环境来避免不同项目间相互干扰。具体做法如下: 创建一个新的 Conda 虚拟环境: ```bash conda create -n myenv python=3.8 conda activate myenv ``` 在新环境中安装所需软件包: ```bash pip install PyMuPDF ``` 此外,为了加速下载过程,可以选择国内镜像源,比如清华 TUNA 提供的服务: ```bash pip install PyMuPDF -i https://pypi.tuna.tsinghua.edu.cn/simple ``` #### 5. **调试打包后的应用程序** 当程序能够正常运行但在打包成可执行文件之后发生此类异常时,需特别注意 pyinstaller 是否完整包含了所有必要的隐含依赖关系。一种可行的办法是在构建命令里加入额外参数以强制包含指定模块: ```bash pyinstaller --hidden-import=fitz.frontend your_script.py ``` --- ### 示例代码片段 假设目标是从 PDF 文件提取图像数据,这里给出一段基于 `PyMuPDF` 实现的功能演示代码: ```python import fitz # PyMuPDF def extract_images_from_pdf(pdf_path): doc = fitz.open(pdf_path) images_list = [] for page_num in range(len(doc)): page = doc.load_page(page_num) image_list = page.get_images(full=True) for img_index, img in enumerate(image_list): xref = img[0] base_image = doc.extract_image(xref) image_data = base_image["image"] with open(f"image_{page_num}_{img_index}.png", "wb") as f: f.write(image_data) images_list.append(f"image_{page_num}_{img_index}.png") return images_list if __name__ == "__main__": pdf_file = "example.pdf" extracted_images = extract_images_from_pdf(pdf_file) print("Extracted Images:", extracted_images) ``` --- ### 总结 综上所述,处理 `ModuleNotFoundError: No module named 'frontend'` 主要集中在以下几个方面:确保正确的库版本、修正不当的导入语法以及优化项目的部署流程。遵循上述指南应能有效缓解这一类技术难题。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值