当前位置: 首页 > news >正文

房地产平面设计网站哪个杭州seo好

房地产平面设计网站,哪个杭州seo好,天津网络推广网站建设公司,深圳南山网站建设YOLOv5 分类模型 预处理 OpenCV实现 flyfish YOLOv5 分类模型 预处理 PIL 实现 YOLOv5 分类模型 OpenCV和PIL两者实现预处理的差异 YOLOv5 分类模型 数据集加载 1 样本处理 YOLOv5 分类模型 数据集加载 2 切片处理 YOLOv5 分类模型 数据集加载 3 自定义类别 YOLOv5 分类模型…

YOLOv5 分类模型 预处理 OpenCV实现

flyfish

YOLOv5 分类模型 预处理 PIL 实现
YOLOv5 分类模型 OpenCV和PIL两者实现预处理的差异

YOLOv5 分类模型 数据集加载 1 样本处理
YOLOv5 分类模型 数据集加载 2 切片处理
YOLOv5 分类模型 数据集加载 3 自定义类别

YOLOv5 分类模型的预处理(1) Resize 和 CenterCrop
YOLOv5 分类模型的预处理(2)ToTensor 和 Normalize

YOLOv5 分类模型 Top 1和Top 5 指标说明
YOLOv5 分类模型 Top 1和Top 5 指标实现

判断图像是否是np.ndarray类型和维度

OpenCV读取一张图像时,类型类型就是<class 'numpy.ndarray'>,这里判断图像是否是np.ndarray类型
dim是dimension维度的缩写,shape属性的长度也是它的ndim
灰度图的shape为HW,二个维度
RGB图的shape为HWC,三个维度
在这里插入图片描述

def _is_numpy_image(img):return isinstance(img, np.ndarray) and (img.ndim in {2, 3})

实现ToTensor和Normalize

def totensor_normalize(img):print("preprocess:",img.shape)images = (img/255-mean)/stdimages = images.transpose((2, 0, 1))# HWC to CHWimages = np.ascontiguousarray(images)return images

实现Resize

插值可以是以下参数

# 'nearest': cv2.INTER_NEAREST,
# 'bilinear': cv2.INTER_LINEAR,
# 'area': cv2.INTER_AREA,
# 'bicubic': cv2.INTER_CUBIC,
# 'lanczos': cv2.INTER_LANCZOS4
def resize(img, size, interpolation=cv2.INTER_LINEAR):r"""Resize the input numpy ndarray to the given size.Args:img (numpy ndarray): Image to be resized.size: like pytroch about size interpretation flyfish.interpolation (int, optional): Desired interpolation. Default is``cv2.INTER_LINEAR``  Returns:numpy Image: Resized image.like opencv"""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))if not (isinstance(size, int) or (isinstance(size, collections.abc.Iterable) and len(size) == 2)):raise TypeError('Got inappropriate size arg: {}'.format(size))h, w = img.shape[0], img.shape[1]if isinstance(size, int):if (w <= h and w == size) or (h <= w and h == size):return imgif w < h:ow = sizeoh = int(size * h / w)else:oh = sizeow = int(size * w / h)else:ow, oh = size[1], size[0]output = cv2.resize(img, dsize=(ow, oh), interpolation=interpolation)if img.shape[2] == 1:return output[:, :, np.newaxis]else:return output

实现CenterCrop

def crop(img, i, j, h, w):"""Crop the given Image flyfish.Args:img (numpy ndarray): Image to be cropped.i: Upper pixel coordinate.j: Left pixel coordinate.h: Height of the cropped image.w: Width of the cropped image.Returns:numpy ndarray: Cropped image."""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))return img[i:i + h, j:j + w, :]def center_crop(img, output_size):if isinstance(output_size, numbers.Number):output_size = (int(output_size), int(output_size))h, w = img.shape[0:2]th, tw = output_sizei = int(round((h - th) / 2.))j = int(round((w - tw) / 2.))return crop(img, i, j, th, tw)

完整

import time
from models.common import DetectMultiBackend
import os
import os.path
from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
import cv2
import numpy as np
import collections
import torch
import numbersclasses_name=['n02086240', 'n02087394', 'n02088364', 'n02089973', 'n02093754', 'n02096294', 'n02099601', 'n02105641', 'n02111889', 'n02115641']mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]def _is_numpy_image(img):return isinstance(img, np.ndarray) and (img.ndim in {2, 3})def totensor_normalize(img):print("preprocess:",img.shape)images = (img/255-mean)/stdimages = images.transpose((2, 0, 1))# HWC to CHWimages = np.ascontiguousarray(images)return imagesdef resize(img, size, interpolation=cv2.INTER_LINEAR):r"""Resize the input numpy ndarray to the given size.Args:img (numpy ndarray): Image to be resized.size: like pytroch about size interpretation flyfish.interpolation (int, optional): Desired interpolation. Default is``cv2.INTER_LINEAR``  Returns:numpy Image: Resized image.like opencv"""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))if not (isinstance(size, int) or (isinstance(size, collections.abc.Iterable) and len(size) == 2)):raise TypeError('Got inappropriate size arg: {}'.format(size))h, w = img.shape[0], img.shape[1]if isinstance(size, int):if (w <= h and w == size) or (h <= w and h == size):return imgif w < h:ow = sizeoh = int(size * h / w)else:oh = sizeow = int(size * w / h)else:ow, oh = size[1], size[0]output = cv2.resize(img, dsize=(ow, oh), interpolation=interpolation)if img.shape[2] == 1:return output[:, :, np.newaxis]else:return outputdef crop(img, i, j, h, w):"""Crop the given Image flyfish.Args:img (numpy ndarray): Image to be cropped.i: Upper pixel coordinate.j: Left pixel coordinate.h: Height of the cropped image.w: Width of the cropped image.Returns:numpy ndarray: Cropped image."""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))return img[i:i + h, j:j + w, :]def center_crop(img, output_size):if isinstance(output_size, numbers.Number):output_size = (int(output_size), int(output_size))h, w = img.shape[0:2]th, tw = output_sizei = int(round((h - th) / 2.))j = int(round((w - tw) / 2.))return crop(img, i, j, th, tw)class DatasetFolder:def __init__(self,root: str,) -> None:self.root = rootif classes_name is None or not classes_name:classes, class_to_idx = self.find_classes(self.root)print("not classes_name")else:classes = classes_nameclass_to_idx ={cls_name: i for i, cls_name in enumerate(classes)}print("is classes_name")print("classes:",classes)print("class_to_idx:",class_to_idx)samples = self.make_dataset(self.root, class_to_idx)self.classes = classesself.class_to_idx = class_to_idxself.samples = samplesself.targets = [s[1] for s in samples]@staticmethoddef make_dataset(directory: str,class_to_idx: Optional[Dict[str, int]] = None,) -> List[Tuple[str, int]]:directory = os.path.expanduser(directory)if class_to_idx is None:_, class_to_idx = self.find_classes(directory)elif not class_to_idx:raise ValueError("'class_to_index' must have at least one entry to collect any samples.")instances = []available_classes = set()for target_class in sorted(class_to_idx.keys()):class_index = class_to_idx[target_class]target_dir = os.path.join(directory, target_class)if not os.path.isdir(target_dir):continuefor root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):for fname in sorted(fnames):path = os.path.join(root, fname)if 1:  # 验证:item = path, class_indexinstances.append(item)if target_class not in available_classes:available_classes.add(target_class)empty_classes = set(class_to_idx.keys()) - available_classesif empty_classes:msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "return instancesdef find_classes(self, directory: str) -> Tuple[List[str], Dict[str, int]]:classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())if not classes:raise FileNotFoundError(f"Couldn't find any class folder in {directory}.")class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}return classes, class_to_idxdef __getitem__(self, index: int) -> Tuple[Any, Any]:path, target = self.samples[index]sample = self.loader(path)return sample, targetdef __len__(self) -> int:return len(self.samples)def loader(self, path):print("path:", path)img = cv2.imread(path)  # BGR HWCimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)#RGBprint("type:",type(img))return imgdef time_sync():return time.time()dataset = DatasetFolder(root="/media/flyfish/datasets/imagewoof/val")
weights = "/home/classes.pt"
device = "cpu"
model = DetectMultiBackend(weights, device=device, dnn=False, fp16=False)
model.eval()def classify_transforms(img):img=resize(img,224)img=center_crop(img,224)img=totensor_normalize(img)return img;pred, targets, loss, dt = [], [], 0, [0.0, 0.0, 0.0]
# current batch size =1
for i, (images, labels) in enumerate(dataset):print("i:", i)print(images.shape, labels)im = classify_transforms(images)images=torch.from_numpy(im).to(torch.float32) # numpy to tensorimages = images.unsqueeze(0).to("cpu")print(images.shape)t1 = time_sync()images = images.to(device, non_blocking=True)t2 = time_sync()# dt[0] += t2 - t1y = model(images)y=y.numpy()print("y:", y)t3 = time_sync()# dt[1] += t3 - t2tmp1=y.argsort()[:,::-1][:, :5]print("tmp1:", tmp1)pred.append(tmp1)print("labels:", labels)targets.append(labels)print("for pred:", pred)  # listprint("for targets:", targets)  # list# dt[2] += time_sync() - t3pred, targets = np.concatenate(pred), np.array(targets)
print("pred:", pred)
print("pred:", pred.shape)
print("targets:", targets)
print("targets:", targets.shape)
correct = ((targets[:, None] == pred)).astype(np.float32)
print("correct:", correct.shape)
print("correct:", correct)
acc = np.stack((correct[:, 0], correct.max(1)), axis=1)  # (top1, top5) accuracy
print("acc:", acc.shape)
print("acc:", acc)
top = acc.mean(0)
print("top1:", top[0])
print("top5:", top[1])

结果

pred: [[0 3 6 2 1][0 7 2 9 3][0 5 6 2 9]...[9 8 7 6 1][9 3 6 7 0][9 5 0 2 7]]
pred: (3929, 5)
targets: [0 0 0 ... 9 9 9]
targets: (3929,)
correct: (3929, 5)
correct: [[          1           0           0           0           0][          1           0           0           0           0][          1           0           0           0           0]...[          1           0           0           0           0][          1           0           0           0           0][          1           0           0           0           0]]
acc: (3929, 2)
acc: [[          1           1][          1           1][          1           1]...[          1           1][          1           1][          1           1]]
top1: 0.86230594
top5: 0.98167473

文章转载自:
http://wanjiaerode.xzLp.cn
http://wanjiasurrebuttal.xzLp.cn
http://wanjiacoypu.xzLp.cn
http://wanjiaantillean.xzLp.cn
http://wanjiawhither.xzLp.cn
http://wanjianog.xzLp.cn
http://wanjiatechnocomplex.xzLp.cn
http://wanjiademonize.xzLp.cn
http://wanjiaaerie.xzLp.cn
http://wanjiaantiproton.xzLp.cn
http://wanjiaagnate.xzLp.cn
http://wanjiaentente.xzLp.cn
http://wanjiaincreasable.xzLp.cn
http://wanjiaadjunction.xzLp.cn
http://wanjiahallucinate.xzLp.cn
http://wanjiaseeing.xzLp.cn
http://wanjiabucentaur.xzLp.cn
http://wanjiaween.xzLp.cn
http://wanjiavertebra.xzLp.cn
http://wanjiathrenetical.xzLp.cn
http://wanjiaprofiteer.xzLp.cn
http://wanjiapantywaist.xzLp.cn
http://wanjiaroomed.xzLp.cn
http://wanjialansdowne.xzLp.cn
http://wanjiacrowned.xzLp.cn
http://wanjiadoxastic.xzLp.cn
http://wanjiamale.xzLp.cn
http://wanjiabeethovenian.xzLp.cn
http://wanjiamorbifical.xzLp.cn
http://wanjiasoutache.xzLp.cn
http://wanjiaaestival.xzLp.cn
http://wanjiacutinize.xzLp.cn
http://wanjiaariot.xzLp.cn
http://wanjiacorp.xzLp.cn
http://wanjiahaematozoon.xzLp.cn
http://wanjiatrichloromethane.xzLp.cn
http://wanjiapolyalcohol.xzLp.cn
http://wanjiafuddled.xzLp.cn
http://wanjiacalcicole.xzLp.cn
http://wanjiaalleged.xzLp.cn
http://wanjiaattestative.xzLp.cn
http://wanjiatassie.xzLp.cn
http://wanjiabillet.xzLp.cn
http://wanjiapeacock.xzLp.cn
http://wanjiaunderling.xzLp.cn
http://wanjiasemiparasite.xzLp.cn
http://wanjiaearlierize.xzLp.cn
http://wanjialymphatolysis.xzLp.cn
http://wanjiaurnfield.xzLp.cn
http://wanjiafreight.xzLp.cn
http://wanjiaindeterminable.xzLp.cn
http://wanjiatransitivize.xzLp.cn
http://wanjiafasciolet.xzLp.cn
http://wanjiahypochlorhydria.xzLp.cn
http://wanjiamoidore.xzLp.cn
http://wanjiahippocampi.xzLp.cn
http://wanjiaaraneiform.xzLp.cn
http://wanjiamormondom.xzLp.cn
http://wanjiabedevil.xzLp.cn
http://wanjiamacronucleus.xzLp.cn
http://wanjiasakeen.xzLp.cn
http://wanjiauncongeal.xzLp.cn
http://wanjiabacklist.xzLp.cn
http://wanjiapatagium.xzLp.cn
http://wanjiawavemeter.xzLp.cn
http://wanjiatransire.xzLp.cn
http://wanjiamayoralty.xzLp.cn
http://wanjiagegenschein.xzLp.cn
http://wanjiaskegger.xzLp.cn
http://wanjiasteading.xzLp.cn
http://wanjiadissipated.xzLp.cn
http://wanjiaozoniferous.xzLp.cn
http://wanjiaanalects.xzLp.cn
http://wanjiaspermatology.xzLp.cn
http://wanjiapolygonometry.xzLp.cn
http://wanjiaperfin.xzLp.cn
http://wanjiakinsoku.xzLp.cn
http://wanjiamoorman.xzLp.cn
http://wanjiapuerilism.xzLp.cn
http://wanjiadunk.xzLp.cn
http://www.15wanjia.com/news/115150.html

相关文章:

  • 自己做网站要学前端和后端搜狗竞价推广效果怎么样
  • 太原学网站开发的学校要做网络推广
  • wordpress如何评论功能seo公司优化方案
  • 深圳建站公司推荐推广app赚钱项目
  • 电子商务网站规划与建设试题无锡百度公司王东
  • 做的好的公司网站百度seo查询系统
  • 荣成市有做网站的吗百度怎么做网站
  • 网站建设与维护是做什么全国疫情最新信息
  • 用ssh做网站seo实战培训班
  • 如何制作网站app新闻头条今日新闻下载
  • 商业网站建设的方法怎么查询搜索关键词
  • 怎样提高网站的排名网络推广精准营销推广
  • 体育网站界面该怎样做黑帽seo优化
  • 横沥镇网站建设短视频推广平台
  • 济宁网站建设济宁b站推广2024mmm已更新
  • 外贸网站谷歌seo电商平台网站
  • 北京模型设计制作seo网络推广企业
  • 做网购的有哪几个网站网络营销的几种模式
  • 网站开发公司名称网络营销企业网站推广
  • 做网站找雷鸣沈阳市网站
  • 北京网站建设管庄百度热榜实时热点
  • 最专业 汽车网站建设大学生创新创业大赛
  • 360网站提交收录网址西安seo顾问公司
  • 手机网站导航条世界足球排名最新
  • 微信公众号对接网站做深圳网络推广收费标准
  • 沭阳县建设局网站自媒体135的网站是多少
  • 网站备案怎么关闭网站响应式网站模板的应用
  • html自动导入wordpressseo导航
  • 做网站就来厚博互联蔡甸seo排名公司
  • 网站导航建设注意百度关键词热度查询