1. numpy
1:numpy:https://www.cnblogs.com/reaptomorrow-flydream/p/9173161.html
2:python x[:] x[::] x[:::]用法,切片和索引
python [:-1] [::-1]的理解(容易混淆)
所以a[::-1]相當於 a[-1:-len(a)-1:-1],也就是從最後一個元素到第一個元素複製一遍。所以你看到一個倒序的東東。
https://blog.csdn.net/qq_21840201/article/details/85084621
https://blog.csdn.net/mingyuli/article/details/81604795
文檔:https://www.runoob.com/numpy/numpy-ndexing-and-slicing.html
#切片操作
#coding=utf-8
import numpy as np
data=np.zeros((2,3,4),np.uint8)
print(data)
print("...")
img=np.ones((3,4),np.uint8)
data[1]=img
print(data)
data[0,...]=img
print(data)
# ::是反轉
import numpy as np
a=[1,2,3.4,5]
print(a)
[ 1 2 3 4 5 ]
print(a[-1]) ###取最後一個元素
[5]
print(a[:-1]) ### 除了最後一個取全部
[ 1 2 3 4 ]
print(a[::-1]) ### 取從後向前(相反)的元素
[ 5 4 3 2 1 ]
print(a[2::-1]) ### 取從下標爲2的元素翻轉讀取
[ 3 2 1 ]
3: np.where(condition, x, y) condition是條件列表,可以多條件
numpy.where多條件查詢
與: numpy.where((con1)*(con2))或者用&
或:numpy.where((con1)|(con2)) (重點:多條件查詢時條件一定要用括號!一定要用括號!一定要用括號!)
參考鏈接:https://www.jb51.net/article/161971.htm
array1=np.where((mask==1)|(mask==2),255,0)
import numpy as np
x = np.arange(16)
a=np.where((x>5)|(x<10))
滿足條件(condition),輸出x,不滿足輸出y。 https://www.cnblogs.com/massquantity/p/8908859.html
4:
import numpy as np
from PIL import Image
a=np.zeros((256,256,3))
b = Image.fromarray(a, mode='RGB')
b.show()
img = np.array(Image.open("lena.jpg"))
#最後將array轉化爲iMage形式
img = Image.fromarray(img.astype('uint8'), mode='RGB')
img.show()
5:省略號與::
https://blog.csdn.net/z13653662052/article/details/78010654
import numpy as np
from PIL import Image
a=np.arange(25).reshape([5,5])
print(a)
print(a[1:3,2:4])
print(a[:,2])
print(a[...,2])
6:python的軸 https://www.cnblogs.com/rrttp/p/8028421.html
7. .join
# -*- coding: UTF-8 -*-
str = "-";
seq = ("a", "b", "c"); # 字符串序列
print str.join( seq );
輸出:a-b-c
8. np.expand_dims
9.np.squeeze
返回:從數組shape中刪除一維項
import numpy as np
x = np.array([[[0], [1], [2]]])
print(x.shape)
d = np.squeeze(x) # 從數組的形狀中刪除單維條目,即把shape中爲1的維度去掉
print(d.shape)
(3,)
10. np.argwhere(a)
返回:非0的數組元素的索引,其中a是待索引數組的條件
import numpy as np
m = np.arange(6).reshape(1,1,6)
print(m)
m=[[[0 1 2 3 4 5]]]
n = np.squeeze(m)#第一維和第二維都是1,故刪除
print(n)
n=[0 1 2 3 4 5]
11. numpy.argmax(a, axis=None, out=None) https://www.cnblogs.com/touch-skyer/p/8509217.html
該函數返回的是數組中最大值的索引值
>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0) #返回行號
array([1, 1, 1])
>>> np.argmax(a, axis=1) #返回列號
array([2, 2])
2. OS模塊:
import os
path=r"F:\wzl\Object-Tracking-master\src\1.png"
print(os.path.split(path)[1])
print(os.path.split(os.path.split(path)[0])[1])
print(os.path.basename(path))
print(os.path.splitext(path)[1])
0. split(str,n) 使用str分割n次,返回一個分割後的列表
>>> "hi.nokia.lumia".split('.',1)[1] ('nokia.lumia')
>>> "hi.nokia.lumia".split('lum',1)[0] ('hi.nokia.')
1. os.path.split(path) 將path分割成目錄和文件名二元組返回。
filepath, tmpfilename = os.path.split(fileUrl) shotname, extension = os.path.splitext(tmpfilename)
>>> os.path.split('c:\\csv\\test.csv') ('c:\\csv', 'test.csv')
>>> os.path.split('c:\\csv\\') ('c:\\csv', '')
2. os.path.splitext(filenames) 分離文件名與擴展名;默認返回(fname,fextension)元組,可做分片操作.
>>> os.path.splitext('c:\\csv\\test.csv')[0] ('c:\\csv\\test', '.csv')
3. os.path.join() 將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略。
>>> os.path.join('c:\\', 'csv', 'test.csv') 'c:\\csv\\test.csv'
4. os.path.basename(path) 返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。
>>> os.path.basename('c:\\test.csv') 'test.csv'
>>> os.path.basename('c:\\csv') 'csv' (這裏csv被當作文件名處理了)
>>> os.path.basename('c:\\csv\\') ''
5. os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False。
6. list2=os.listdir(list1) new=sorted(list2,key=lambda i:int((i.split(".")[0]).split("_")[1])) 提取並根據文件名排序;
文件名 mask_10.bmp
7. filenames=os.listdir(dir) filenames.sort(key=lambda x:int(x[:-4]))#倒着數第四位'.'爲分界線,按照‘.’左邊的數字從小到大排序
8. join https://www.cnblogs.com/ling-yu/p/9167065.html
參考鏈接:https://www.cnblogs.com/wuxie1989/p/5623435.html
import os
print(os.path.split('C:/soft/python/test.py')[1]) #test.py
print(os.path.split('C:/soft/python/test')) #test
可以遍歷找到所有路徑含某字符的文件
def findfile(self,keyword,root):
filelist=[]
for root,dirs,files in os.walk(root):
for name in files:
fitfile=filelist.append(os.path.join(root, name))
#print(fitfile)
#print(os.path.join(root, name))
#print(filelist)
print('...........................................')
for i in filelist:
if os.path.isfile(i):
#print(i)
if keyword in os.path.split(i)[0]:
print('yes!',i) # 絕對路徑
#else:
#print('......no keyword!')
3. lambda
from functools import reduce
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print (list(filter(lambda x: x % 3 == 0, foo)))
#[18, 9, 24, 12, 27]
print (list(map(lambda x: x * 2 + 10, foo)))
#[14, 46, 28, 54, 44, 58, 26, 34, 64]
print (reduce(lambda x, y: x + y, foo))
#139
上述用for....in...if表示:
print ([x * 2 + 10 for x in foo]) 非常的簡潔,易懂。
filter的例子可以寫成:print ([x for x in foo if x % 3 == 0]) 同樣也是比lambda的方式更容易理解。
4 txt文件寫入
import os
data=[]
data.append(str(1))
data.append("...")
data.append("name")
with open("data.txt",'w') as f:
f.writelines(data)
w.write('\r\n')#換行
5 shutil
import shutil
argetdir_path = 'W:\\Solar\\' + upfile
Targetfile_path = 'W:\\Solar\\' + upfile + '\\' + data_name
if not os.path.exists(Targetdir_path):
os.mkdir(Targetdir_path)
shutil.copyfile(file, Targetfile_path)
6 find
常用於os模塊中路徑特定字符查找,找到該字符返回索引位置,否則返回-1 。
str='F:\術前\3 MR OSag T2'
print(str.find("術前"))
print(str[:str.find("術前")+2])
#F:\術前
7. 一種查找替換numpy數組矩陣符合條件的方法,參考np.where
#和np.where測試代碼
img1=np.random.randint(0,3,(2,2,3))
print("img1:::")
print(img1)
print(img1.shape)
# print("......")
# img=np.arange(24).reshape(2,2,3,2)
# print(img.shape)
# print(img)
print("..............................")
img=img1[1,:,:]
print("img.shape",img.shape)
print("img",img)
#img2=np.where(img>1,255,0)
#print(img2)
pre=np.zeros_like(img,dtype=np.uint8)
pre[img>1]=255
print(pre)
8 關鍵字排序sorted
# 用第二個關鍵字排過序後再用第一個關鍵字進行排序
L = [('d',2),('a',4),('b',3),('c',2)]
print sorted(L, key=lambda x:(x[1],x[0]),reverse=False)
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]
for j in range(0, len(contours)):
area = cv2.contourArea(contours[j])
M = cv2.moments(contours[j])
cX = int(M["m10"] / (M["m00"] + 0.000001))
cY = int(M["m01"] / (M["m00"] + 0.000001))
cnt_tuples.append((j, area, cX, cY))
cnt_tuples = sorted(cnt_tuples, key=lambda x: x[1], reverse=True)
9. filter map reduce配合lamda:https://www.cnblogs.com/caizhao/p/7905094.html https://www.cnblogs.com/caizhao/p/7905094.html
foo=[1,2,4,3,53,234]
# list1=[x for x in foo if x%2==0]
# opencv輪廓檢測中可以相對輪廓面積長度排序,然後filter篩選
# cnt_tuples.append((j, area, cX, cY))
# cnt_tuples = sorted(cnt_tuples, key=lambda x: x[1], reverse=True)
print(list(map(lambda x: x * x, [y for y in range(3)])))
print(list(filter(lambda x:x%2==0,foo)))
#測試二
import numpy as np
import os
list1=np.random.randint(1,3,[3,4])
print(list1)
list2=np.arange(1,15,2)
print(list2)
list3=list(map(lambda x: x*x , list2))
print(list3)
list4=list(filter(lambda x:x%2==0,list2))
print(list4)
六劍客鏈接:https://www.cnblogs.com/xiaxiaoxu/p/9740086.html
other:練習小程序
# 邊界提取 https://blog.csdn.net/weixin_38517705/article/details/84670150
import numpy as np
import cv2
import os
def face2line(dirFile,suffix,newDirFile):
'''把dirFile文件夾下的類別圖轉化成邊界圖
dirFile:指定的被轉化的圖片所在的文件夾
suffix:圖片類型,如“tif"
newDirFile:轉化出來的圖片所要存的文件夾
'''
if(os.path.exists(newDirFile)==False):
os.mkdir(newDirFile)
for file in os.listdir(dirFile):
singleFileName=dirFile+"\\"+file
singlefileForm = os.path.splitext(singleFileName)[1][1:]
if(singlefileForm == suffix):
print('loading................ : ',singleFileName)
img=cv2.imread(singleFileName,0)
edge=np.zeros((img.shape[0],img.shape[1]),np.int8)
for i in range(1,img.shape[0]-1):
for j in range(1,img.shape[1]-1):
#if (img[i,j]==255&img[i+1,j]==0)|(img[i,j]==255&img[i-1,j]==0):
if (img[i,j]==255 and img[i+1,j]==0) or(img[i,j]==255 and img[i-1,j]==0):
edge[i,j]=255
if (img[i,j]==255 and img[i,j+1]==0) or(img[i,j]==255 and img[i,j-1]==0):
edge[i,j]=255
cv2.imwrite(newDirFile+"\\"+file,edge)
numpy遍歷圖像操作:
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
#讀取原始圖像
img = cv2.imread('miao.png')
#圖像灰度轉換
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#獲取圖像高度和寬度
height = grayImage.shape[0]
width = grayImage.shape[1]
#創建一幅圖像
result = np.zeros((height, width), np.uint8)
#圖像灰度非線性變換:DB=DA×DA/255
for i in range(height):
for j in range(width):
gray = int(grayImage[i,j])*int(grayImage[i,j]) / 255
result[i,j] = np.uint8(gray)
#顯示圖像
cv2.imshow("Gray Image", grayImage)
cv2.imshow("Result", result)
#等待顯示
cv2.waitKey(0)
cv2.destroyAllWindows()
10. np.concatenate
import numpy as np
# a=np.array([[1,2,3],[4,5,6]])
# b=np.array([[11,21,31],[7,8,9]])
# c=np.concatenate((a,b),axis=0)
# print(c)
a=np.random.randint(0,3,(1,3,3,2))
b=np.random.randint(5,8,(1,3,3,2))
c=np.concatenate((a,b),axis=0)
print(c)
print(c.shape) # (2, 3, 3, 2)
11. np.random
from skimage import io,data
import numpy as np
img=data.chelsea()
#隨機生成5000個椒鹽,因爲是3通道,所以是rows,cols,dims=img.shape,如果是灰度圖則只有兩通道則rows,cols=img.shape
rows,cols,dims=img.shape
for i in range(5000):
x=np.random.randint(0,rows)
y=np.random.randint(0,cols)
img[x,y,:]=255
io.imshow(img)