图片数据归一化normalize(python脚本)

调用opencv的normalize函数完成图片数据归一化到0-1的值,最后再乘以255.
版本:python3.6

import os  
import io  
import math
import sys
import cv2
import shutil
import random
import numpy as np
from collections import namedtuple, OrderedDict  

label_names = ['person','car','bus','truck','motorcycle','chemical']

def get_files(dir, suffix): 

    res = []

    for root, directory, files in os.walk(dir): 

        for filename in files:

            name, suf = os.path.splitext(filename) 

            if suf in suffix:
                #res.append(filename)

                res.append(os.path.join(root, filename))
    return res

def uniform_image_size(list_path,width_size,height_size):
    image_list = get_files(list_path, ['.jpg'])
    total_len = len(image_list)
    print('total_label_len', total_len)
    for i in range(0, total_len):
        image_file = image_list[i]
        img = cv2.imread(image_file)
        cv2.imshow("input", img)
        cv2.waitKey(1)
        result = np.zeros(img.shape, dtype=np.float32)
        cv2.normalize(img, result, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
        print(result)
        cv2.imshow("norm", np.uint8(result*255.0))
        cv2.waitKey(1)
        os.remove(image_file)
        cv2.imwrite(image_file, np.uint8(result*255.0))
    cv.destroyAllWindows()

def main():  

    list_path = r'E:\projection\fair\yunfuyanhuo5'

    width_size = 1280
    height_size = 720

    uniform_image_size(list_path,width_size,height_size)

if __name__ == '__main__':  

    main()
### 如何对COCO数据集的标签文件进行归一化处理 对于对象检测或图像处理任务,在使用像COCO这样的大型数据集时,通常需要将边界框坐标标准化以便于模型训练。这有助于提高模型收敛速度并改善性能。 在COCO数据集中,标注是以绝对像素值给出的。为了实现归一化,可以按照如下方式转换: - 将边界框的宽度和高度除以对应图片的实际宽度和高度。 - 中心点位置同样按比例缩放至范围 `[0, 1]`之间。 具体操作可以通过Python脚本完成,下面是一个简单的例子来展示如何读取原始JSON格式的COCO标注文件并对其中的对象边界框执行上述变换: ```python import json def normalize_bbox(bbox, img_width, img_height): """Normalize bbox coordinates.""" x_min, y_min, width, height = bbox # Convert to center point format and scale down by image dimensions x_center = (x_min + width / 2) / img_width y_center = (y_min + height / 2) / img_height norm_width = width / img_width norm_height = height / img_height return [x_center, y_center, norm_width, norm_height] with open('annotations/instances_train2017.json') as f: coco_data = json.load(f) for annotation in coco_data['annotations']: img_info = next(item for item in coco_data['images'] if item["id"] == annotation['image_id']) original_bbox = annotation['bbox'] normalized_bbox = normalize_bbox(original_bbox, img_info['width'], img_info['height']) print(f'Original BBox: {original_bbox}, Normalized BBox: {normalized_bbox}') ``` 这段代码遍历所有的注解项,并针对每张图片的信息调整其对应的边界框尺寸[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值