numpy.fliplr()用法

本文详细解析np.fliplr()函数,展示如何在不同维度上实现矩阵的左右翻转,特别适用于图像处理中水平翻转的需求。通过具体示例说明了在二维及更高维度下该函数的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

np.fliplr()

矩阵左右翻转,在二维的情况下很容易理解。维度更高的话一开始没有搞懂,实际也挺简单。
在这里插入图片描述
原来矩阵的写成下面这样:

[   [[0,1], [2, 3]]
	[[4,5], [6, 7]] ]

[0, 1], [2, 3], [4, 5], [6, 7] 看成二维情况下的一个数。那么左右交换就是 [2, 3][0, 1] 交换…
最后变成:

[   [[2, 3], [0, 1]]
	[[6, 7], [4, 5]] ]

用于图像的水平翻转

对图像进行翻转,只需要将图像每个通道的矩阵左右翻转即可。

def fliplr(x):
    if x.ndim == 3:
        x = np.transpose(np.fliplr(np.transpose(x, (0, 2, 1))), (0, 2, 1))
    elif x.ndim == 4:
        for i in range(x.shape[0]):
            x[i] = np.transpose(
                np.fliplr(np.transpose(x[i], (0, 2, 1))), (0, 2, 1))
    return x.astype(float)
img = torch.from_numpy(fliplr(img.numpy())).float()

img 是一个tensor,C x H x W. 将img转换为 ndarray 作为fliplr函数的参数.
上面如果没有np.transpose,就是将图像上下翻转了。

github: skipping check (not a git repository) YOLOv5 2021-4-11 torch 2.7.1+cpu CPU Namespace(weights='weights/yolov5s.pt', cfg='models/yolov5s_kouzhao.yaml', data='data/kouzhao.yaml', hyp='data/hyp.scratch.yaml', epochs=300, batch_size=8, img_s ize=[640, 640], rect=False, resume=False, nosave=False, notest=False, noautoanchor=False, evolve=False, bucket='', cache_images=False, image_weights=False, devic e='', multi_scale=False, single_cls=False, adam=False, sync_bn=False, local_rank=-1, workers=8, project='runs/train', entity=None, name='exp', exist_ok=False, qu ad=False, linear_lr=False, label_smoothing=0.0, upload_dataset=False, bbox_interval=-1, save_period=-1, artifact_alias='latest', world_size=1, global_rank=-1, save_dir='runs\\train\\exp', total_batch_size=8) tensorboard: Start with 'tensorboard --logdir runs/train', view at http://localhost:6006/ hyperparameters: lr0=0.01, lrf=0.2, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1. 0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0 Traceback (most recent call last): File "D:\Code\yolov5\train.py", line 543, in <module> train(hyp, opt, device, tb_writer) File "D:\Code\yolov5\train.py", line 71, in train run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None ^^^^^^^^^^^^^^^^^^^ File "D:\Editor\anaconda3\envs\yolov5-5.0\Lib\site-packages\torch\serialization.py", line 1524, in load raise pickle.UnpicklingError(_get_wo_message(str(e))) from None _pickle.UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint. (1) In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source. (2) Alternatively, to load with `weights_only=True` please check the recommended steps in the following error message. WeightsUnpickler error: Unsupported global: GLOBAL numpy.core.multiarray._reconstruct was not an allowed global by default. Please use `torch.serializati on.add_safe_globals([numpy.core.multiarray._reconstruct])` or the `torch.serialization.safe_globals([numpy.core.multiarray._reconstruct])` context manager to allowlist this global if you trust this class/function. Check the documentation of torch.load to learn more about types accepted by default with weights_only https://pytorch.org/docs/stable/generated/torch.load.html.
最新发布
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值