Loading... # python索引 `用于记录python在深度学习中的使用` 使用到的场景是从本地opencv读取一张图片,需要将图片由bgr格式转为rgb格式。github上有些代码是`cv2.cvtColor(img,cv2.COLOR_BGR2RGB)`而有一些“调皮”的作者喜欢直接用索引 `img=img[:,:,::-1]` 结果都是一样的,那么`img[:,:,::-1]`具体是什么意思 # python 索引用法 这些都是字符串、数组、列表切片的意思,代表索引出某些值 其中有几种格式 > s[index] —— 返回索引值为 index 的那个字符 > s[start:] —— 返回从索引值为 start 开始一直到字符串末尾的所有字符 > s[start:stop] —— 返回从索引值为 start 开始一直到索引值为 stop的那个字符之前的所有字符 > s[:stop] —— 返回从字符串开头一直到索引值为 stop 的那个字符之前的所有字符 > s[start:stop:step] —— 返回从索引值为 start 开始一直到索引值为 stop 的那个字符之前的,以 step为步长提取的所有字符 # 举例子 ## s[::-1] 就是从最后一位到最前一位的索引。 ```python s="abcd" #字符串 print(s[::-1]) num=[1,2,3,4] #数组列表 print(num[::-1]) ``` **输出** ```python dcba [4, 3, 2, 1] ``` ## [1::2] 就是从索引1开始,步长为2,取到结束 ```python s="abcd" #字符串 print(s[1::2]) num=[1,2,3,4] #数组列表 print(num[1::2]) ``` **输出** ```python bd [2, 4] ``` ## img[:,:,::-1] opencv数组格式为h,w,c。因此这句话就是h,w不变,c通道从后往前读,本来是`BGR` 变成 `RGB` ```python import cv2 import numpy as np img = np.random.randn(112,112,3).astype(np.float32) #print(img) img1 = img[:,:,::-1] img2=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) assert np.allclose( img1, img2, rtol=1e-3, atol=1e-3), 'The outputs are different' print('The numerical values are same') ``` **输出** ```python The numerical values are same ``` 最后修改:2025 年 02 月 22 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏