ModuleNotFoundError: No module named ‘podm.metrics‘报错等解决方法
ModuleNotFoundError: No module named 'podm.metrics’报错等解决方法
podm.metrics
在运行时报错:
ModuleNotFoundError: No module named ‘podm.metrics’
安装了podm
后还是报错
解决方法:
查看安装位置
查看podm
的安装位置,并打开到该位置(ctrl+点击位置):
pip show podm
新建metrics文件
在该位置下找到podm
文件夹,发现其中没有metrics.py
文件,故新建该文件
并将一下代码粘贴在文件中:
import sys
from collections import Counter, defaultdict
from enum import Enum
from typing import List, Dict, Any, Tupleimport numpy as npfrom podm import box
from podm.coco import PCOCOObjectDetectionDataset, PCOCOBoundingBox, PCOCOSegmentsclass BoundingBox(box.Box):"""image: image.category: category.xtl: the X top-left coordinate of the bounding box.ytl: the Y top-left coordinate of the bounding box.xbr: the X bottom-right coordinate of the bounding box.ybr: the Y bottom-right coordinate of the bounding box.score: (optional) the confidence of the detected class."""def __init__(self):super(BoundingBox, self).__init__()self.image = Noneself.category = Noneself.score = None # type: float or None@classmethoddef of_bbox(cls, image, category, xtl: float, ytl: float, xbr: float, ybr: float, score: float = None) \-> 'BoundingBox':bbox = BoundingBox()bbox.xtl = xtlbbox.ytl = ytlbbox.xbr = xbrbbox.ybr = ybrbbox.image = imagebbox.score = scorebbox.category = categoryreturn bboxdef get_bounding_boxes(dataset: PCOCOObjectDetectionDataset, use_name: bool = True) -> List[BoundingBox]:bboxes = []for ann in dataset.annotations:if isinstance(ann, PCOCOBoundingBox):bb = BoundingBox.of_bbox(ann.image_id, ann.category_id, ann.xtl, ann.ytl, ann.xbr, ann.ybr, ann.score)elif isinstance(ann, PCOCOSegments):bb = BoundingBox.of_bbox(ann.image_id, ann.category_id,ann.bbox.xtl, ann.bbox.ytl, ann.bbox.xbr, ann.bbox.ybr, ann.score)else:raise TypeErrorif use_name:bb.image = dataset.get_image(id=ann.image_id).file_namebb.category = dataset.get_category(id=ann.category_id).namebboxes.append(bb)return bboxesclass MethodAveragePrecision(Enum):"""Class representing if the coordinates are relative to theimage size or are absolute values.Developed by: Rafael PadillaLast modification: Apr 28 2018"""AllPointsInterpolation = 1ElevenPointsInterpolation = 2class MetricPerClass:def __init__(self):self.label = Noneself.precision = Noneself.recall = Noneself.ap = Noneself.interpolated_precision = None # type: None or np.ndarrayself.interpolated_recall = None # type: None or np.ndarrayself.num_groundtruth = Noneself.num_detection = Noneself.tp = Noneself.fp = None@staticmethoddef mAP(results: Dict[Any, 'MetricPerClass']):return np.average([m.ap for m in results.values() if m.num_groundtruth > 0])def get_pascal_voc_metrics(gold_standard: List[BoundingBox],predictions: List[BoundingBox],iou_threshold: float = 0.5,method: MethodAveragePrecision = MethodAveragePrecision.AllPointsInterpolation) -> Dict[str, MetricPerClass]:"""Get the metrics used by the VOC Pascal 2012 challenge.Args:gold_standard: ground truth bounding boxes;predictions: detected bounding boxes;iou_threshold: IOU threshold indicating which detections will be considered TP or FP (default value = 0.5);method: It can be calculated as the implementation in the official PASCAL VOC toolkit (EveryPointInterpolation),or applying the 11-point interpolation as described in the paper "The PASCAL Visual Object Classes(VOC)Challenge" or AllPointsInterpolation" (ElevenPointInterpolation);Returns:A dictionary containing metrics of each class."""ret = {} # list containing metrics (precision, recall, average precision) of each class# Get all classescategories = sorted(set(b.category for b in gold_standard + predictions))# Precision x Recall is obtained individually by each class# Loop through by classesfor category in categories:preds = [b for b in predictions if b.category == category] # type: List[BoundingBox]golds = [b for b in gold_standard if b.category == category] # type: List[BoundingBox]npos = len(golds)# sort detections by decreasing confidencepreds = sorted(preds, key=lambda b: b.score, reverse=True)tps = np.zeros(len(preds))fps = np.zeros(len(preds))# create dictionary with amount of gts for each imagecounter = Counter([cc.image for cc in golds])for key, val in counter.items():counter[key] = np.zeros(val)# Pre-processing groundtruths of the some imageimage_name2gt = defaultdict(list)for b in golds:image_name2gt[b.image].append(b)# Loop through detectionsfor i in range(len(preds)):# Find ground truth imagegt = image_name2gt[preds[i].image]max_iou = sys.float_info.minmas_idx = -1for j in range(len(gt)):iou = box.intersection_over_union(preds[i], gt[j])if iou > max_iou:max_iou = ioumas_idx = j# Assign detection as true positive/don't care/false positiveif max_iou >= iou_threshold:if counter[preds[i].image][mas_idx] == 0:tps[i] = 1 # count as true positivecounter[preds[i].image][mas_idx] = 1 # flag as already 'seen'else:# - A detected "cat" is overlaped with a GT "cat" with IOU >= IOUThreshold.fps[i] = 1 # count as false positiveelse:fps[i] = 1 # count as false positive# compute precision, recall and average precisioncumulative_fps = np.cumsum(fps)cumulative_tps = np.cumsum(tps)recalls = np.divide(cumulative_tps, npos, out=np.full_like(cumulative_tps, np.nan), where=npos != 0)precisions = np.divide(cumulative_tps, (cumulative_fps + cumulative_tps))# Depending on the method, call the right implementationif method == MethodAveragePrecision.AllPointsInterpolation:ap, mrec, mpre, _ = calculate_all_points_average_precision(recalls, precisions)else:ap, mrec, mpre = calculate_11_points_average_precision(recalls, precisions)# add class result in the dictionary to be returnedr = MetricPerClass()r.label = categoryr.precision = precisionsr.recall = recallsr.ap = apr.interpolated_recall = np.array(mrec)r.interpolated_precision = np.array(mpre)r.tp = np.sum(tps)r.fp = np.sum(fps)r.num_groundtruth = len(golds)r.num_detection = len(preds)ret[category] = rreturn retdef calculate_all_points_average_precision(recall: List[float], precision: List[float]) \-> Tuple[float, List[float], List[float], List[int]]:"""All-point interpolated average precisionReturns:average precisioninterpolated recallinterpolated precisioninterpolated points"""mrec = [0.0] + [e for e in recall] + [1.0]mpre = [0.0] + [e for e in precision] + [0]for i in range(len(mpre) - 1, 0, -1):mpre[i - 1] = max(mpre[i - 1], mpre[i])ii = []for i in range(len(mrec) - 1):if mrec[i + 1] != mrec[i]:ii.append(i + 1)ap = 0for i in ii:ap = ap + np.sum((mrec[i] - mrec[i - 1]) * mpre[i])return ap, mrec[0:len(mpre) - 1], mpre[0:len(mpre) - 1], iidef calculate_11_points_average_precision(recall: List[float], precision: List[float]) -> Tuple[float, List[float], List[float]]:"""11-point interpolated average precision. This is done by segmenting the recalls evenly into 11 parts:{0,0.1,0.2,...,0.9,1}.Args:recall: recall listprecision: precision listReturns:average precision, interpolated recall, interpolated precision"""mrec = [e for e in recall]mpre = [e for e in precision]recall_values = np.linspace(0, 1, 11)recall_values = list(recall_values[::-1])rho_interp = []recall_valid = []# For each recallValues (0, 0.1, 0.2, ... , 1)for r in recall_values:# Obtain all recall values higher or equal than rarg_greater_recalls = np.argwhere(mrec[:] >= r)pmax = 0# If there are recalls above rif arg_greater_recalls.size != 0:pmax = max(mpre[arg_greater_recalls.min():])recall_valid.append(r)rho_interp.append(pmax)# By definition AP = sum(max(precision whose recall is above r))/11ap = sum(rho_interp) / 11# Generating values for the plotrvals = [recall_valid[0]] + [e for e in recall_valid] + [0]pvals = [0] + [e for e in rho_interp] + [0]# rhoInterp = rhoInterp[::-1]cc = []for i in range(len(rvals)):p = (rvals[i], pvals[i - 1])if p not in cc:cc.append(p)p = (rvals[i], pvals[i])if p not in cc:cc.append(p)recall_values = [i[0] for i in reversed(cc)]precision_values = [i[1] for i in reversed(cc)]return ap, recall_values, precision_values
podm.box
报错:
ModuleNotFoundError: No module named ‘podm.coco’
新建coco.py
文件,并添加以下内容:
from enum import Enum
from typing import Tupleclass Box:"""0,0 ------> x (width)|| (Left,Top)| *_________| | || |y |_________|(height) *(Right,Bottom)xtl: the X top-left coordinate of the bounding box.ytl: the Y top-left coordinate of the bounding box.xbr: the X bottom-right coordinate of the bounding box.ybr: the Y bottom-right coordinate of the bounding box."""def __init__(self):self.xtl = None # type: float or Noneself.ytl = None # type: float or Noneself.xbr = None # type: float or Noneself.ybr = None # type: float or None@classmethoddef of_box(cls, xtl: float, ytl: float, xbr: float, ybr: float) -> 'Box':""":param xtl: the X top-left coordinate of the bounding box.:param ytl: the Y top-left coordinate of the bounding box.:param xbr: the X bottom-right coordinate of the bounding box.:param ybr: the Y bottom-right coordinate of the bounding box."""box = Box()box.xtl = xtlbox.ytl = ytlbox.xbr = xbrbox.ybr = ybrbox.verify()return boxdef set_box(self, box: 'Box'):self.xtl = box.xtlself.ytl = box.ytlself.xbr = box.xbrself.ybr = box.ybrdef verify(self):assert self.xtl <= self.xbr, f'xtl < xbr: xtl:{self.xtl}, xbr:{self.xbr}'assert self.ytl <= self.ybr, f'ytl < ybr: ytl:{self.ytl}, xbr:{self.ybr}'@propertydef segment(self):return [self.xtl, self.ytl, self.xtl, self.ybr, self.xbr, self.ybr, self.xbr, self.ytl]@propertydef width(self) -> float:return self.xbr - self.xtl@propertydef height(self) -> float:return self.ybr - self.ytl@propertydef area(self) -> float:return (self.xbr - self.xtl) * (self.ybr - self.ytl)@propertydef center(self) -> Tuple[float, float]:return (self.xbr + self.xtl) / 2, (self.ybr + self.ytl) / 2def __contains__(self, item):if not type(item) == list and not type(item) == tuple:raise TypeError('Has to be a list or a tuple: %s' % type(item))if len(item) == 2:return self.xtl <= item[0] < self.xbr and self.ytl <= item[1] < self.ybrelse:raise ValueError('Only support a point')def __str__(self):return 'Box[xtl={},ytl={},xbr={},ybr={}]'.format(self.xtl, self.ytl, self.xbr, self.ybr)def __eq__(self, other):if not isinstance(other, Box):return Falsereturn self.xtl == other.xtl and self.ytl == other.ytl and self.xbr == other.xbr and self.ybr == other.ybrdef intersection_over_union(box1: 'Box', box2: 'Box') -> float:"""Intersection Over Union (IOU) is measure based on Jaccard Index that evaluates the overlap betweentwo bounding boxes."""# if boxes dont intersectif not is_intersecting(box1, box2):return 0intersection_area = intersection(box1, box2).areaunion = union_areas(box1, box2, intersection_area=intersection_area)# intersection over unioniou = intersection_area / unionassert iou >= 0, '{} = {} / {}, box1={}, box2={}'.format(iou, intersection, union, box1, box2)return ioudef is_intersecting(box1: 'Box', box2: 'Box') -> bool:if box1.xtl > box2.xbr:return False # boxA is right of boxBif box2.xtl > box1.xbr:return False # boxA is left of boxBif box1.ybr < box2.ytl:return False # boxA is above boxBif box1.ytl > box2.ybr:return False # boxA is below boxBreturn Truedef union_areas(box1: 'Box', box2: 'Box', intersection_area: float = None) -> float:if intersection_area is None:intersection_area = intersection(box1, box2).areareturn box1.area + box2.area - intersection_areadef union(box1: 'Box', box2: 'Box'):xtl = min(box1.xtl, box2.xtl)ytl = min(box1.ytl, box2.ytl)xbr = max(box1.xbr, box2.xbr)ybr = max(box1.ybr, box2.ybr)return Box.of_box(xtl, ytl, xbr, ybr)def intersection(box1: 'Box', box2: 'Box'):xtl = max(box1.xtl, box2.xtl)ytl = max(box1.ytl, box2.ytl)xbr = min(box1.xbr, box2.xbr)ybr = min(box1.ybr, box2.ybr)return Box.of_box(xtl, ytl, xbr, ybr)class BBFormat(Enum):"""Class representing the format of a bounding box.It can be (X,Y,width,height) => XYWHor (X1,Y1,X2,Y2) => XYX2Y2Developed by: Rafael PadillaLast modification: May 24 2018"""XYWH = 1X1Y1X2Y2 = 2# class BoundingBox(Box):
# def __init__(self):
# """Constructor.
# Args:
# image: image.
# category: category.
# xtl: the X top-left coordinate of the bounding box.
# ytl: the Y top-left coordinate of the bounding box.
# xbr: the X bottom-right coordinate of the bounding box.
# ybr: the Y bottom-right coordinate of the bounding box.
# score: (optional) the confidence of the detected class.
# """
# super(BoundingBox, self).__init__()
# self.image = None
# self.category = None
# self.score = None # type: float or None
#
# @classmethod
# def of_bbox(cls, image, category, xtl: float, ytl: float, xbr: float, ybr: float, score: float = None) \
# -> 'BoundingBox':
# bbox = BoundingBox()
# bbox.xtl = xtl
# bbox.ytl = ytl
# bbox.xbr = xbr
# bbox.ybr = ybr
# bbox.image = image
# bbox.score = score
# bbox.category = category
# return bbox
podm.coco_decoder
新建coco_decoder.py
文件,并添加代码:
import copy
import json
from typing import Dictfrom podm.coco import PCOCOLicense, PCOCOInfo, PCOCOImage, PCOCOCategory, PCOCOBoundingBox, PCOCOSegments, \PCOCOObjectDetectionDatasetdef parse_infon(obj: Dict) -> PCOCOInfo:info = PCOCOInfo()info.contributor = obj['contributor']info.description = obj['description']info.url = obj['url']info.date_created = obj['date_created']info.version = obj['version']info.year = obj['year']return infodef parse_license(obj: Dict) -> PCOCOLicense:lic = PCOCOLicense()lic.id = obj['id']lic.name = obj['name']lic.url = obj['url']return licdef parse_image(obj: Dict) -> PCOCOImage:img = PCOCOImage()img.id = obj['id']img.height = obj['height']img.width = obj['width']img.file_name = obj['file_name']img.flickr_url = obj['flickr_url']img.coco_url = obj['coco_url']img.date_captured = obj['date_captured']img.license = obj['license']return imgdef parse_bounding_box(obj: Dict) -> PCOCOBoundingBox:ann = PCOCOBoundingBox()ann.id = obj['id']ann.category_id = obj['category_id']ann.image_id = obj['image_id']ann.xtl = obj['bbox'][0]ann.ytl = obj['bbox'][1]ann.xbr = ann.xtl + obj['bbox'][2]ann.ybr = ann.ytl + obj['bbox'][3]if 'contributor' in obj:ann.contributor = obj['contributor']if 'score' in obj:ann.score = obj['score']if 'attributes' in obj:ann.attributes = obj['attributes']return anndef parse_segments(obj: Dict) -> PCOCOSegments:ann = PCOCOSegments()ann.id = obj['id']ann.category_id = obj['category_id']ann.image_id = obj['image_id']ann.iscrowd = obj['iscrowd']ann.segmentation = obj['segmentation']if 'score' in obj:ann.score = obj['score']if 'contributor' in obj:ann.contributor = obj['contributor']if 'attributes' in obj:ann.attributes = obj['attributes']return anndef parse_category(obj: Dict) -> PCOCOCategory:cat = PCOCOCategory()cat.id = obj['id']cat.name = obj['name']cat.supercategory = obj['supercategory']return catdef parse_object_detection_dataset(coco_obj: Dict) -> PCOCOObjectDetectionDataset:dataset = PCOCOObjectDetectionDataset()dataset.info = parse_infon(coco_obj['info'])for lic_obj in coco_obj['licenses']:lic = parse_license(lic_obj)dataset.licenses.append(lic)for img_obj in coco_obj['images']:img = parse_image(img_obj)dataset.images.append(img)for ann_obj in coco_obj['annotations']:if 'segmentation' in ann_obj and len(ann_obj['segmentation']) > 0:ann = parse_segments(ann_obj)else:ann = parse_bounding_box(ann_obj)dataset.add_annotation(ann)for cat_obj in coco_obj['categories']:cat = parse_category(cat_obj)dataset.categories.append(cat)return datasetdef load_true_object_detection_dataset(fp, **kwargs) -> PCOCOObjectDetectionDataset:coco_obj = json.load(fp, **kwargs)return parse_object_detection_dataset(coco_obj)def load_pred_object_detection_dataset(fp, dataset: PCOCOObjectDetectionDataset, **kwargs) \-> PCOCOObjectDetectionDataset:new_dataset = PCOCOObjectDetectionDataset()new_dataset.info = copy.deepcopy(dataset.info)new_dataset.licenses = copy.deepcopy(dataset.licenses)new_dataset.images = copy.deepcopy(dataset.images)new_dataset.categories = copy.deepcopy(dataset.categories)# check annotationcoco_obj = json.load(fp, **kwargs)annotations = []for obj in coco_obj:ann = parse_bounding_box(obj)if new_dataset.get_image(id=ann.image_id) is None:print('%s: Cannot find image' % ann.image_id)if new_dataset.get_category(id=ann.category_id) is None:print('%s: Cannot find category' % ann.category_id)annotations.append(ann)new_dataset.annotations = annotationsreturn new_dataset
podm.coco_encoder
新建coco_encoder.py
文件,并添加以下代码:
import json
from typing import Union, TextIO, Dict, Listfrom podm.coco import PCOCOImage, PCOCOLicense, PCOCOInfo, \PCOCOCategory, PCOCOBoundingBox, \PCOCOSegments, PCOCOObjectDetectionDatasetPCOCO_OBJ = Union[PCOCOImage, PCOCOLicense, PCOCOInfo,PCOCOCategory,PCOCOObjectDetectionDataset,List[PCOCOBoundingBox],
]class PCOCOJSONEncoder(json.JSONEncoder):"""Extensible BioC JSON encoder for BioC data structures."""def default(self, o):# print('xxxxxxxxxxxxxxxxxxxx')# print(type(o))# print(isinstance(o, PCOCOObjectDetectionDataset))# print(repr(o.__class__), repr(PCOCOObjectDetectionResult))if isinstance(o, PCOCOImage):return {"width": o.width,"height": o.height,"flickr_url": o.flickr_url,"coco_url": o.coco_url,"file_name": o.file_name,"date_captured": o.date_captured,"license": o.license,"id": o.id,}if isinstance(o, PCOCOLicense):return {"id": o.id,"name": o.name,"url": o.url,}if isinstance(o, PCOCOInfo):return {"year": o.year,"version": o.version,"description": o.description,"contributor": o.contributor,"url": o.url,"date_created": o.date_created,}if isinstance(o, PCOCOCategory):return {"id": o.id,"name": o.name,"supercategory": o.supercategory,}if isinstance(o, PCOCOBoundingBox):return {"id": o.id,"image_id": o.image_id,"category_id": o.category_id,"bbox": [o.xtl, o.ytl, o.width, o.height],"score": o.score,"contributor": o.contributor,"attributes": json.dumps(o.attributes)}if isinstance(o, PCOCOSegments):bb = o.bboxreturn {"id": o.id,"image_id": o.image_id,"category_id": o.category_id,"segmentation": o.segmentation,"bbox": [bb.xtl, bb.ytl, bb.width, bb.height],"area": bb.area,"iscrowd": o.iscrowd,"score": o.score,"contributor": o.contributor,"attributes": json.dumps(o.attributes)}if isinstance(o, PCOCOObjectDetectionDataset):return {"info": self.default(o.info),'images': [self.default(img) for img in o.images],"licenses": [self.default(l) for l in o.licenses],'annotations': [self.default(ann) for ann in o.annotations],'categories': [self.default(cat) for cat in o.categories],}# Let the base class default method raise the TypeErrorreturn json.JSONEncoder.default(self, o)def toJSON(o) -> Dict:"""Convert a pcoco obj to a Python `dict`"""return PCOCOJSONEncoder().default(o)def dumps(obj: PCOCO_OBJ, **kwargs) -> str:"""Serialize a BioC ``obj`` to a JSON formatted ``str``. kwargs are passed to json."""return json.dumps(obj, cls=PCOCOJSONEncoder, indent=2, **kwargs)def dump(obj: PCOCO_OBJ, fp: TextIO, **kwargs):"""Serialize ``obj`` as a JSON formatted stream to ``fp``(a ``.write()``-supporting file-like object). kwargs are passed to json."""return json.dump(obj, fp, cls=PCOCOJSONEncoder, indent=2, **kwargs)```## podm.coco新建`coco.py`文件,并添加:```pythonimport copy
from abc import ABC
from typing import List, Tuple, Set, Collection
from datetime import date, datetime
from shapely.geometry import Polygon, Point
from podm import boxclass PCOCOInfo:def __init__(self):self.year = date.today().year # type:intself.version = '' # type: strself.description = '' # type: strself.contributor = '' # type: strself.url = '' # type: strself.date_created = datetime.now().strftime('%m/%d/%Y') # type:strclass PCOCOAnnotation(ABC):def __init__(self):self.id = None # type:int or Noneself.image_id = None # type:int or Noneself.score = None # type:float or Noneself.contributor = '' # type: strself.attributes = {} # type: dictclass PCOCOImage:def __init__(self):self.id = None # type:int or Noneself.width = 0 # type:intself.height = 0 # type:intself.file_name = '' # type:strself.license = None # type:int or Noneself.flickr_url = '' # type:strself.coco_url = '' # type:strself.date_captured = datetime.now().strftime('%m/%d/%Y') # type:strclass PCOCOLicense:def __init__(self):self.id = None # type:int or Noneself.name = '' # type:strself.url = '' # type:strclass PCOCOCategory:def __init__(self):self.id = None # type:int or Noneself.name = '' # type:strself.supercategory = '' # type:strclass PCOCODataset(ABC):def __init__(self):self.info = PCOCOInfo() # type: PCOCOInfo or Noneself.images = [] # type: List[PCOCOImage]self.licenses = [] # type: List[PCOCOLicense]def add_license(self, license: PCOCOLicense):for lic in self.licenses:if lic.id == license.id or lic.name == license.name:raise KeyError('%s: License exists' % lic.id)self.licenses.append(license)def add_image(self, image: PCOCOImage):for img in self.images:if img.id == image.id or img.file_name == image.file_name:raise KeyError('%s: Image exists' % img.id)self.images.append(image)def get_image(self, id: int = None, file_name: str = None, default=None) -> PCOCOImage:if id is None and file_name is None:raise KeyError('%s %s: Cannot set both to None' % (id, file_name))if id is not None and file_name is not None:raise KeyError('%s %s: Cannot set both' % (id, file_name))imgs = self.imagesif id is not None:imgs = [img for img in imgs if img.id == id]if len(imgs) == 0:return defaultelif len(imgs) == 1:return next(iter(imgs))else:raise KeyError('%s: more than one image with the same id' % id)if file_name is not None:imgs = [img for img in imgs if img.file_name == file_name]if len(imgs) == 0:return defaultelif len(imgs) == 1:return next(iter(imgs))else:raise KeyError('%s: more than one image with the same name' % file_name)raise Exception('Should not be here')def get_images(self, ids: Collection[int] = None) -> List[PCOCOImage]:"""Load anns with the specified ids.:param ids: integer ids specifying img:return: imgs: loaded img objects"""return [img for img in self.images if img.id in ids]##############################################################################
# object detection
##############################################################################class PCOCOBoundingBox(PCOCOAnnotation, box.Box):def __init__(self):super(PCOCOBoundingBox, self).__init__()self.category_id = None # type:int or Noneclass PCOCOSegments(PCOCOAnnotation):def __init__(self):super(PCOCOSegments, self).__init__()self.category_id = None # type:int or Noneself.segmentation = [] # type: List[List[float]]self.iscrowd = False # type:booldef add_box(self, box: box.Box):self.add_segmentation(box.segment)def add_segmentation(self, segmentation: List[float]):self.segmentation.append(segmentation)def __contains__(self, item):if not type(item) == list and not type(item) == tuple:raise TypeError('Has to be a list or a tuple: %s' % type(item))if len(item) == 2:point = Point(item[0], item[1])for p in self.polygons:if p.contains(point):return Truereturn Falseelse:raise ValueError('Only support a point')@propertydef polygons(self) -> List[Polygon]:return [Polygon([(seg[i], seg[i+1]) for i in range(0, len(seg), 2)]) for seg in self.segmentation]@propertydef bbox(self) -> 'box.Box' or None:if len(self.segmentation) == 0:return Noneelse:b = self.box_polygon(self.segmentation[0])for polygon in self.segmentation[1:]:b = box.union(b, self.box_polygon(polygon))return b@classmethoddef box_polygon(cls, polygon: List[float]) -> 'box.Box':xtl = min(polygon[i] for i in range(0, len(polygon), 2))ytl = min(polygon[i] for i in range(1, len(polygon), 2))xbr = max(polygon[i] for i in range(0, len(polygon), 2))ybr = max(polygon[i] for i in range(1, len(polygon), 2))return box.Box.of_box(xtl, ytl, xbr, ybr)class PCOCOImageCaptioning(PCOCOAnnotation):def __init__(self):super(PCOCOImageCaptioning, self).__init__()self.caption = None # type:str or Noneclass PCOCOObjectDetectionDataset(PCOCODataset):def __init__(self):super(PCOCOObjectDetectionDataset, self).__init__()self.annotations = [] # type: List[PCOCOBoundingBox or PCOCOSegments]self.categories = [] # type: List[PCOCOCategory]def add_annotation(self, annotation: 'PCOCOBoundingBox' or 'PCOCOSegments'):for ann in self.annotations:if ann.id == annotation.id:raise KeyError('%s: Annotation exists' % ann.id)self.annotations.append(annotation)def add_category(self, category: PCOCOCategory):for cat in self.categories:if cat.id == category.id or cat.name == category.name:raise KeyError('%s: Category exists' % cat.id)self.categories.append(category)def get_max_category_id(self):return max(cat.id for cat in self.categories)def get_category(self, id: int = None, name: str = None, default=None) -> PCOCOCategory:if id is None and name is None:raise KeyError('%s %s: Cannot set both to None' % (id, name))if id is not None and name is not None:raise KeyError('%s %s: Cannot set both' % (id, name))cats = self.categoriesif id is not None:cats = [cat for cat in cats if cat.id == id]if len(cats) == 0:return defaultelif len(cats) == 1:return next(iter(cats))else:raise KeyError('%s: more than one category with the same id' % id)if name is not None:cats = [cat for cat in cats if cat.name == name]if len(cats) == 0:return defaultelif len(cats) == 1:return next(iter(cats))else:raise KeyError('%s: more than one category with the same name' % name)raise Exception('Should not be here')def get_annotation(self, id: int, default=None) -> PCOCOAnnotation:anns = [ann for ann in self.annotations if ann.id == id]if len(anns) == 0:return defaultelif len(anns) == 1:return next(iter(anns))else:raise KeyError('%s: more than one annotation' % id)def get_new_dataset(self, annotations: Collection[PCOCOBoundingBox or PCOCOSegments]):new_dataset = PCOCOObjectDetectionDataset()new_dataset.info = copy.deepcopy(self.info)new_dataset.licenses = copy.deepcopy(self.licenses)new_dataset.images = copy.deepcopy(self.images)new_dataset.categories = copy.deepcopy(self.categories)for ann in annotations:new_dataset.add_annotation(ann)return new_datasetdef get_category_ids(self, category_names: Collection[str] = None,supercategory_names: Collection[str] = None) -> Collection[int]:"""filtering parameters. default skips that filter.:param category_names: get cats for given cat names:param supercategory_names: get cats for given supercategory names:return: integer array of cat ids"""itr = iter(self.categories)if category_names is not None:itr = filter(lambda x: x.name in category_names, itr)if supercategory_names is not None:itr = filter(lambda x: x.supercategory in supercategory_names, itr)return [cat.id for cat in itr]def get_annotation_ids(self, image_ids: Collection[int] = None,category_ids: Collection[int] = None,area_range: Tuple[float, float] = None) -> Collection[int]:"""Get ann ids that satisfy given filter conditions. default skips that filter:param image_ids: get anns for given imgs:param category_ids: get anns for given cats:param area_range: get anns for given area range (e.g. [0 inf]):return: integer array of ann ids"""# image_ids = convert_array_argument(image_ids)# category_ids = convert_array_argument(category_ids)# area_range = convert_array_argument(area_range)itr = iter(self.annotations)if image_ids is not None:itr = filter(lambda x: x.image_id in image_ids, itr)if category_ids is not None:itr = filter(lambda x: x.category_id in category_ids, itr)if area_range is not None:itr = filter(lambda x: area_range[0] <= x.area <= area_range[1], itr)return [ann.id for ann in itr]def get_image_ids(self, category_ids: Collection[int] = None) -> Collection[int]:"""Get img ids that satisfy given filter conditions.:param category_ids: get imgs with all given cats:return: ids: integer array of img ids"""ids = set(img.id for img in self.images)for i, cat_id in enumerate(category_ids):if i == 0 and len(ids) == 0:ids = set(ann.image_id for ann in self.annotations if ann.category_id == cat_id)else:ids &= set(ann.image_id for ann in self.annotations if ann.category_id == cat_id)return list(ids)def get_annotations(self, ids: Collection[int] = None) -> Collection[PCOCOAnnotation]:"""Load anns with the specified ids.:param ids: integer ids specifying anns:return: anns: loaded ann objects"""return [ann for ann in self.annotations if ann.id in ids]def get_categories(self, ids: Collection[int] = None) -> Collection[PCOCOCategory]:"""Load cats with the specified ids.:param ids: integer ids specifying cats:return: cats: loaded cat objects"""return [cat for cat in self.categories if cat.id in ids]
podm.coco2labelme
新建coco2labelme.py
文件,并添加代码:
from podm.coco import PCOCOObjectDetectionDataset, PCOCOBoundingBox, PCOCOSegmentsdef coco2labelme(cocodataset: PCOCOObjectDetectionDataset):objs = []for img in cocodataset.images:obj = {"version": "5.0.1","flags": {},"imagePath": img.file_name,"imageData": None,"imageHeight": img.height,"imageWidth": img.width,"shapes": []}for annid in cocodataset.get_annotation_ids(image_ids=[img.id]):ann = cocodataset.get_annotation(annid)if isinstance(ann, PCOCOBoundingBox):shape = {"label": ann.attributes['ID'],"points": [[ann.xtl, ann.ytl], [ann.xbr, ann.ybr]],"group_id": None,"shape_type": "rectangle","flags": {}}elif isinstance(ann, PCOCOSegments):shape = {"label": ann.attributes['ID'],"points": [[ann.segmentation[0][i], ann.segmentation[0][i+1]]for i in range(0, len(ann.segmentation[0]), 2)],"group_id": None,"shape_type": "polygon","flags": {}}else:raise TypeErrorobj['shapes'].append(shape)objs.append(obj)return objs
podm.pascal2coco
新建pascal2coco.py
文件,并添加以下代码:
"""
Convert from a PASCAL VOC zip file to a COCO file.Usage:pascal2coco gold --gold=<file> --output-gold=<file>pascal2coco pred --gold=<file> --pred=<file> --output-gold=<file> --output-pred=<file>Options:--gold=<file> PASCAL VOC groundtruths zip file--pred=<file> PASCAL VOC predictions zip file--output-gold=<file> Groundtruths JSON file--output-pred=<file> Predictions JSON file
"""
import json
import zipfile
import io
import warningsimport docopt
import tqdm
import pandas as pd
from podm import coco_encoder
from podm.box import BBFormat, Box
from podm.coco import PCOCOObjectDetectionDataset, PCOCOImage, PCOCOCategory, PCOCOBoundingBoxdef convert_pascal_to_df(src):rows = []with zipfile.ZipFile(src, 'r') as myzip:namelist = myzip.namelist()for name in tqdm.tqdm(namelist):if not name.endswith('.txt'):continuewith myzip.open(name, 'r') as fp:name = name[name.find('/') + 1:]items_file = io.TextIOWrapper(fp)for line in items_file:toks = line.strip().split(' ')if len(toks) == 5:row = {'name': name,'label': toks[0],'xtl': int(toks[1]),'ytl': int(toks[2]),'xbr': int(toks[3]),'ybr': int(toks[4])}elif len(toks) == 6:row = {'name': name,'label': toks[0],'score': float(toks[1]),'xtl': int(toks[2]),'ytl': int(toks[3]),'xbr': int(toks[4]),'ybr': int(toks[5])}else:raise ValueErrorrows.append(row)return pd.DataFrame(rows)class PascalVoc2COCO:def __init__(self, format: BBFormat = BBFormat.X1Y1X2Y2):self.format = formatdef convert_gold(self, src) -> PCOCOObjectDetectionDataset:df = convert_pascal_to_df(src)dataset = PCOCOObjectDetectionDataset()# add imagefor i, name in enumerate(df['name'].unique()):img = PCOCOImage()img.id = iimg.file_name = namedataset.add_image(img)# add categoryfor i, label in enumerate(df['label'].unique()):cat = PCOCOCategory()cat.id = icat.name = labeldataset.add_category(cat)# add annotationfor i, row in tqdm.tqdm(df.iterrows(), total=len(df)):box = Box.of_box(row['xtl'], row['ytl'], row['xbr'], row['ybr'])if self.format == BBFormat.XYWH:box.xbr += box.xtlbox.ybr += box.ytlann = PCOCOBoundingBox()ann.image_id = dataset.get_image(file_name=row['name']).idann.id = iann.category_id = dataset.get_category(name=row['label']).idann.set_box(box)dataset.add_annotation(ann)return datasetdef convert_gold_file(self, src, dest):dataset = self.convert_gold(src)with open(dest, 'w') as fp:coco_encoder.dump(dataset, fp)def convert_gold_pred(self, src_gold, src_pred):gold_dataset = self.convert_gold(src_gold)df = convert_pascal_to_df(src_pred)# check catsubrows = []for i, row in tqdm.tqdm(df.iterrows(), total=len(df)):if gold_dataset.get_category(name=row['label']) is None:warnings.warn('%s: Category does not exist' % row['label'])continueif gold_dataset.get_image(file_name=row['name']) is None:warnings.warn('%s: Image does not exist' % row['name'])continuesubrows.append(row)if len(subrows) < len(df):warnings.warn('Remove %s rows' % (len(df) - len(subrows)))annotations = []for i, row in tqdm.tqdm(enumerate(subrows), total=len(subrows)):box = Box.of_box(row['xtl'], row['ytl'], row['xbr'], row['ybr'])if self.format == BBFormat.XYWH:box.xbr += box.xtlbox.ybr += box.ytlann = PCOCOBoundingBox()ann.image_id = gold_dataset.get_image(file_name=row['name']).idann.id = iann.category_id = gold_dataset.get_category(name=row['label']).idann.score = row['score']ann.set_box(box)annotations.append(ann)pred_dataset = gold_dataset.get_new_dataset(annotations)return gold_dataset, pred_datasetdef convert_gold_pred_file(self, src_gold, src_pred, dest_gold, dest_pred):gold_dataset, pred_dataset = self.convert_gold_pred(src_gold, src_pred)with open(dest_gold, 'w') as fp:coco_encoder.dump(gold_dataset, fp)with open(dest_pred, 'w') as fp:json.dump(pred_dataset.annotations, fp, cls=coco_encoder.PCOCOJSONEncoder, indent=2)def main():argv = docopt.docopt(__doc__)converter = PascalVoc2COCO(BBFormat.X1Y1X2Y2)if argv['gold']:converter.convert_gold_file(argv['--gold'], argv['--output-gold'])if argv['pred']:converter.convert_gold_pred_file(argv['--gold'], argv['--pred'], argv['--output-gold'], argv['--output-pred'])if __name__ == '__main__':main()
最终文件夹内容
最终文件夹中内容如下:
相关文章:
ModuleNotFoundError: No module named ‘podm.metrics‘报错等解决方法
ModuleNotFoundError: No module named podm.metrics’报错等解决方法 podm.metrics 在运行时报错: ModuleNotFoundError: No module named ‘podm.metrics’ 安装了podm后还是报错 解决方法: 查看安装位置 查看podm的安装位置,并打开到该…...
Java虚拟机运行时数据区域(内存模型)
程序计数器(线程私有内存) What:程序计数器是一块较小的内存空间,可以看作是当前线程所执行的字节码的行号指示器。 程序控制流的指示器, 分支,循环,跳转,异常处理,线程…...
trf 4.10安装与使用-生信工具42
01 背景 DNA 中的串联重复(Tandem Repeat)指的是两个或多个相邻且近似的核苷酸模式的拷贝。Tandem Repeats Finder (TRF) 是一个程序,用于定位并显示 DNA 序列中的串联重复。用户只需提交一个以 FASTA 格式编写的序列,无需指定重…...
rom定制系列------小米max3安卓12 miui14批量线刷 默认开启usb功能选项 插电自启等
小米Max3是小米公司于2018年7月19日发布的机型。此机型后在没有max新型号。采用全金属一体机身设计,配备6.9英寸全面屏.八核处理器骁龙636,后置双摄像头1200万500万像素,前置800万像素.机型代码 :nitrogen.官方最终版为稳定版12.5…...
PySide6-UI界面设计
导论: PySide6和PyQt都是Python对Qt框架的绑定,允许开发者使用Qt创建平台的GUI应用程序。如果你正在开发商业项目,或者需要使用最新的QT6特性,PySide6是一个更好的选择。如果你更倾向于一个成熟的社区和丰富的资源,Py…...
Java创建线程的方式有哪些?
创建线程的方式 1. 继承 Thread 类 在 Java 中,当你启动一个线程时,实际上是调用了 Thread 类的 start() 方法。这个方法会执行以下几个步骤: 线程的状态转变:调用 start() 方法后,线程的状态从 NEW 转变为 RUNNABL…...
Ubuntu | PostgreSQL | 解决 ERROR: `xmllint` is missing on your system.
解决 sudo apt install apt-file sudo apt-file updatesudo apt-file search xmllint sudo apt install libxml2-utils执行 # postgres源码安装包解压文件夹中 make install make install问题 make -C src install make[2]: Entering directory /home/postgres/postgresql-1…...
Jenkins pipeline 发送邮件及包含附件
Jenkins pipeline 发送邮件及包含附件 设置邮箱开启SMTP服务 此处适用163 邮箱 开启POP3/SMTP服务通过短信获取TOKEN (保存TOKEN, 后面Jenkins会用到) Jenkins 邮箱设置 安装 Build Timestamp插件 设置全局凭证 Dashboard -> Manage Jenkins …...
基于深度学习的视觉检测小项目(十) 通过样式表改变界面的外观
一、创建色卡模板文件 在PS中打开之前创建的色卡文件,用吸管拾色器吸取各个色卡的色彩值: 并保存为JSON文件,color_card.json,文件保存在项目的/settings目录下: {"colors": {"RED": "#dc1…...
【Java基础】Stream流、文件File相关操作,IO的含义与运用
1. Java 流(Stream)、文件(File)和IO Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。Java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。 一个流可以理解为一个数据的序列。 输入流表…...
Java-日志-Slf4j-Log4j-logback
文章目录 SLF4J基础概念使用输出形式日志绑定桥接旧的框架实战 logback基础概念配置文件 Log4j概述 SLF4J 参考: https://www.cnblogs.com/shenStudy/p/15806951.html https://slf4j.org/ 基础概念 是什么?SLF4J(Simple Logging Facade fo…...
探索式测试
探索式测试是一种软件测试风格,它强调独立测试人员的个人自由和职责,为了持续优化其工作的价值,将测试学习、测试设计、测试执行和测试结果分析作为相互支持的活动,在整个项目实现过程中并行地执行。 选择合适的探索式测试方法我…...
LeetCode LCP17速算机器人
速算机器人:探索字符指令下的数字变换 在编程的奇妙世界里,我们常常会遇到各种有趣的算法问题,这些问题不仅考验我们的逻辑思维,还能让我们感受到编程解决实际问题的魅力。今天,就让我们一同探讨一个关于速算机器人的…...
Taro+Vue实现图片裁剪组件
cropper-image-taro-vue3 组件库 介绍 cropper-image-taro-vue3 是一个基于 Vue 3 和 Taro 开发的裁剪工具组件,支持图片裁剪、裁剪框拖动、缩放和输出裁剪后的图片。该组件适用于 Vue 3 和 Taro 环境,可以在网页、小程序等平台中使用。 源码 https:…...
ISP各模块功能介绍
--------声明,本文为转载整理------- ISP各个模块功能介绍: 各模块前后效果对比: 黑电平补偿(BLC) 在理想情况下,没有光照射的像素点其响应值应为0。但是,由于杂质、受热等其它原因的影响&…...
SQL-leetcode-584. 寻找用户推荐人
584. 寻找用户推荐人 表: Customer -------------------- | Column Name | Type | -------------------- | id | int | | name | varchar | | referee_id | int | -------------------- 在 SQL 中,id 是该表的主键列。 该表的每一行表示一个客户的 id、姓名以及推…...
新冠肺炎服务预约微信小程序的设计与实现ssm+论文源码调试讲解
第4章 系统设计 4.1 系统设计的原则 在系统设计过程中,也需要遵循相应的设计原则,这些设计原则可以帮助设计者在短时间内设计出符合设计规范的设计方案。设计原则主要有可靠性,安全性,可定制化,可扩展性,可…...
多模态人工智能在零售业的未来:通过GPT-4 Vision和MongoDB实现智能产品发现
多模态人工智能在零售业的未来:通过GPT-4 Vision和MongoDB实现智能产品发现 引言 想象一下,顾客在购物时只需上传一张他们所期望的服装或产品的照片,几分钟内便能收到来自他们最喜欢的商店的个性化推荐。这就是多模态人工智能在零售领域所带…...
3D目标检测数据集——kitti数据集
KITTI官网网址:The KITTI Vision Benchmark Suite 下载数据集:The KITTI Vision Benchmark Suite KITTI数据集论文:CMSY9 github可视化代码:GitHub - kuixu/kitti_object_vis: KITTI Object Visualization (Birdview, Volumetric LiDar point cloud )...
从CentOS到龙蜥:企业级Linux迁移实践记录(系统安装)
引言: 随着CentOS项目宣布停止维护CentOS 8并转向CentOS Stream,许多企业和组织面临着寻找可靠替代方案的挑战。在这个背景下,龙蜥操作系统(OpenAnolis)作为一个稳定、高性能且完全兼容的企业级Linux发行版࿰…...
Cocos二维Slider
1、可拖动区域计算 根据UI的世界坐标了宽高信息计算出handle的坐标范围 this.posMin new Vec2(this.node.worldPosition.x - this.uiSelf.contentSize.width * 0.5, this.node.worldPosition.y - this.uiSelf.contentSize.height * 0.5); this.posMax new Vec2(this.node.w…...
kubeneters-循序渐进Cilium网络(二)
文章目录 概要IP 地址配置接口配置解析结论 概要 接续前一章节,我们还是以这张图继续深入Cilium网络世界 IP 地址配置 通过检查 Kubernetes 集群的当前环境,可以获取实际的 IP 地址和配置信息。这些信息将被补充到之前的网络示意图中,以使…...
【再谈设计模式】模板方法模式 - 算法骨架的构建者
一、引言 在软件工程、软件开发过程中,我们经常会遇到一些算法或者业务逻辑具有固定的流程步骤,但其中个别步骤的实现可能会因具体情况而有所不同的情况。模板方法设计模式(Template Method Design Pattern)就为解决这类问题提供了…...
[开源]自动化定位建图系统(视频)
系统状态机: 效果展示: 1、 机器人建图定位系统-基础重定位,定位功能演示 2、 机器人建图定位系统-增量地图构建,手动回环检测演示 3、… 开源链接: https://gitee.com/li-wenhao-lwh/lifelong-backend Qt人机交互…...
Kali系统(Debian 10.3) 遇到的问题
目录 问题一:非问题 kali 基础官网与安装 问题二: 问题三: Kali系统 MySQL问题Cant connect to local MySQL server through socket /run/mysqld/mysqld.sock (2) 问题四:重新安装MySQL 也就是MariaDB(MariaDB 含 MySQL相关…...
P2249 【深基13.例1】查找
题目描述 输入 n 个不超过 109 的单调不减的(就是后面的数字不小于前面的数字)非负整数 a1,a2,…,an,然后进行 m 次询问。对于每次询问,给出一个整数 q,要求输出这个数字在序列中第一次出现的编号,如…...
【时时三省】(C语言基础)常见的动态内存错误3
山不在高,有仙则名。水不在深,有龙则灵。 ----CSDN 时时三省 对同一块动态内存多次释放 示例: 解决方法就是释放完把p等于空指针就好了 动态开辟的空间忘记释放 示例: 只有p能找到这块空间 只有p知道这块动态开辟的空间起始地…...
Three.js 性能优化:打造流畅高效的3D应用
文章目录 前言一、减少几何体复杂度(Reduce Geometry Complexity)二、合并几何体(Merge Geometries)三、使用缓冲区几何体(Use BufferGeometries)四、纹理压缩与管理(Texture Compression and M…...
CancerGPT :基于大语言模型的罕见癌症药物对协同作用少样本预测研究
今天我们一起来剖析一篇发表于《npj Digital Medicine》的论文——《CancerGPT for few shot drug pair synergy prediction using large pretrained language models》。该研究聚焦于一个极具挑战性的前沿领域:如何利用大语言模型(LLMs)在数…...
Clisoft SOS与CAD系统集成
Clisoft SOS与CAD系统集成 以下内容大部分来自官方文档,目前只用到与Cadence Virtuoso集成,其他还未用到,如有问题或相关建议,可以留言。 与Keysight ADS集成 更新SOS客户端配置文件sos.cfg,以包含支持ADS的模板&am…...
基于 GEE 下载逐年 MODIS 地表温度 LST 数据
目录 1 地表温度(LST) 2 数据准备 3 代码实现 3.1 加载研究区与数据集 3.2 数据预处理与标准化 3.3 逐年批量导出 3.4 可视化结果 4 运行结果 5 完整代码 1 地表温度(LST) 在遥感领域,地表温度(L…...
ISP图像调优流程
第一步:亮度调试 AE:ae目标值,ae权重表,ae曝光策略,ae收敛速度 .ae容忍值 ae权重表:中央区域权重,均值权重等。感兴趣的区域往AE目标亮度靠近 ae目标亮度: AE 目标亮度是随着增益升高而降低的。 AE 目标亮度的调整主要是看图像的过曝区大小是否达到要求(如对比机)…...
SpringBoot多数据源架构实现
文章目录 1. 环境准备2. 创建Spring Boot项目3. 添加依赖4. 配置多数据源5. 配置MyBatis-Plus6. 使用多数据源7. 创建Mapper接口8. 实体类定义9. 测试多数据源10. 注意事项10.1 事务导致多数据源失效问题解决方案: 10.2 ClickHouse的事务支持10.3 数据源切换的性能开…...
VAxios
VAxios(或v-axios)是一个基于Axios的Vue插件,旨在让开发者在Vue项目中更方便、快捷地引入和使用Axios。以下是对VAxios的详细介绍: 一、功能与特性 VAxios作为Axios的Vue封装插件,继承了Axios的众多特性,…...
macOS安装nvm
新建一个文件夹,使用git将nvm给clone下来 git clone https://github.com/nvm-sh/nvm.git 使用vim编辑~/.bash_profile文件(没有就新建)添加以下代码 export NVM_DIR"$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] &&…...
每日算法Day14【删除二叉搜索树中的节点、修剪二叉搜索树、将有序数组转换为二叉搜索树、把二叉搜索树转换为累加树】
450.删除二叉搜索树中的节点 算法链接: 450. 删除二叉搜索树中的节点 - 力扣(LeetCode) 类型: 二叉树 难度: 中等 思路:两层判断,第一层判断节点与key大小,如果节点删除则判断其左右子节点情况;如果只有一…...
【数据分析(一)】初探 Numpy
目录 前言1. 一维 array 的生成2. 一维 array 的基本操作2.1. 查看属性2.2. 花式索引2.3. 条件筛查2.4. 数据统计 3. n 维 array 的生成4. n 维 array 的基本操作4.1. 查看属性4.2. 查询和切片4.3. 花式索引4.4. 矩阵 前言 Numpy是Python的常用开源数值计算扩展库,用…...
蓝桥杯嵌入式速通(1)
1.工程准备 创建一文件夹存放自己的代码,并在mdk中include上文件夹地址 把所有自身代码的头文件都放在headfile头文件中,之后只需要在新的文件中引用headfile即可 headfile中先提前可加入 #include "stdio.h" #include "string.h"…...
深度解析如何使用Linux中的git操作
1.如何理解版本控制 →Git&&gitee||github 多版本控制面对善变的甲方 版本控制是一种用于管理文件或代码变更的系统,帮助团队或个人追踪项目的历史记录,并支持多方协作开发。它在软件开发和文档管理中尤为重要,但也适用于其他需要追…...
青龙面板脚本开发指南:高效自动化任务的实现
青龙面板脚本开发指南:高效自动化任务的实现 青龙面板(Qinglong Panel)是一款强大的任务管理平台,支持多种语言的脚本开发和执行。通过在青龙面板中编写和管理脚本,用户可以轻松实现自动化任务,提高工作效…...
视频编辑最新SOTA!港中文Adobe等发布统一视频生成传播框架——GenProp
文章链接:https://arxiv.org/pdf/2412.19761 项目链接:https://genprop.github.io 亮点直击 定义了一个新的生成视频传播问题,目标是利用 I2V 模型的生成能力,将视频第一帧的各种变化传播到整个视频中。 精心设计了模型 GenProp&…...
ue5动画重定向,一键重定向。ue4小白人替换成ue5
这就是我们下载的 初学者动画内容包 点击设置选中列 绿色的是动画 黄色的关卡 蓝色是蓝图 ctrla 全选 ctrl鼠标左键 选中所有动画 重定向动画资产 不要选错,只要绿色 选择目标网格体 选择所有的绿色 动画 导出动画 添加前缀ycn 导出 一定要提前新建好存放的…...
C++ 枚举类型
【语法解析】 ● C 枚举类型 在C中,枚举(enumeration)类型是一种简单的数据类型,用于定义在程序中使用的常量。(1)枚举类型的定义格式:enum <类型名> {<枚举常量表>};(2…...
通过Apache、Nginx限制直接访问public下的静态文件
一、Apache 在public目录下的.htaccess文件中添加如下规则,来拒绝除了指定文件类型之外的所有请求 <FilesMatch "\.(?!(jpg|jpeg|png|gif|css|js|ico)$)[^.]$">Order Allow,DenyDeny from all </FilesMatch> 上述配置表示仅允许访问.jpg …...
Spring Boot3 配合ProxySQL实现对 MySQL 主从同步的读写分离和负载均衡
将 ProxySQL 配合 Spring Boot 使用,主要的目的是在 Spring Boot 应用程序中实现对 MySQL 主从同步的读写分离和负载均衡。这样,你可以利用 ProxySQL 自动将写操作路由到主库,而将读操作路由到从库。 1. 准备工作 确保你的 MySQL 主从同步环…...
ubuntu20下编译linux1.0 (part1)
author: hjjdebug date: 2025年 01月 09日 星期四 15:56:15 CST description: ubuntu20下编译linux1.0 (part1) 该博客记录了新gcc编译旧代码可能碰到的问题和解决办法, 可留作参考 操作环境: ubuntu20 $ gcc --version gcc (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0 $ as --vers…...
【AI日记】25.01.10
【AI论文解读】【AI知识点】【AI小项目】【AI战略思考】【AI日记】【读书与思考】 AI kaggle 比赛:Forecasting Sticker Sales 读书 书名:国家为什么会失败阅读原因:2024 年诺贝尔经济学奖得主的力作未删减版:https://book.dou…...
04_Redis数据类型-String字符串
1.Redis数据类型介绍 Redis是一种Key-Value类型缓存型数据库,Redis为了存储不同类型的数据,Value支持多种数据类型,Redis为我们提供了常用的9种数据类型。包括5种基本类型:String(字符串)、Hash(哈希)、List(列表),Set(集合)及zset(Sorted Set有序集合);和4种…...
mysql之基本select语句 运算符 排序分页
1.SQL的分类 DDL:数据定义语言. CREATE ALTER DROP RENAME TRUNCATE DML: 数据操作语言. INSERT DELETE UPDATE SELECT 重中之重 DCL: 数据控制语言. COMMIT ROLLBACK SAVEPOINT GRANT REVOKE 2.SQL语言的规则与规范 1.基本规则 SQL可以在一行或多行,为了提高可…...
springboot整合admin
1. 添加依赖 首先,在你的admin服务端pom.xml文件中添加Spring Boot Admin的依赖: <dependency><groupId>de.codecentric</groupId><artifactId>spring-boot-admin-starter-server</artifactId><version>2.5.4<…...