openCV Code
cv2 v.s. PIL
特性 | cv2 | PIL |
---|---|---|
打開圖像 | cv2.imread(‘test.jpg’) | Image.open(‘test.jpg’) |
圖像模式 | BGR | RGB |
圖像尺寸 | h, w, c = image.shape | w, h = image.size |
縮放 | im =cv2.resize(img2,(h,w)) 或者 im =cv2.resize(img2,None,fx,fy) fx,fy是縮放因子 |
im = img1.resize((w,h)) |
保存 | cv2.imwrite(path,img) | img1.save(path) |
轉NumPy | 無需轉換 | image = np.array(image,dtype=np.float32) # 默認是uint8 維度變成(h,w,c)了 注意ndarray中是 行row x 列col x 維度dim 所以行數是高,列數是寬 |
獲取像素 | img[h,w,c] | im.getpixel((w,h)) |
說明 | 應該是先高後寬 | 總是先寬後高 |
參考:
OpenCV、Skimage、PIL圖像處理的細節差異
PIL:Image 和 cv2簡單比較
cv2.resize(img, (0, 0), fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC)
cv2.resize(img, None, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC)
caffe前向過程
# test for MobileNet
import numpy as np
import cv2
import caffe
MODEL_FILE = './V2/mobilenet_deploy.prototxt'
PRETRAIN_FILE = r'./V2/MNext_iter_6000.caffemodel'
caffe.set_mode_cpu()
net = caffe.Net(MODEL_FILE, PRETRAIN_FILE, caffe.TEST)
mean_vec = np.array([103.94, 116.78, 123.68], dtype=np.float32)
reshaped_mean_vec = mean_vec.reshape(1, 1, 3)
im = cv2.imread(impath)
im = cv2.resize(im, (160, 120))
im = im[60-56:60+56, 80-56:80+56, ...]
im = im - reshaped_mean_vec
im *= 0.017
im = im.transpose((2, 0, 1))
im_ = np.zeros((1, 3, 112, 112), dtype=np.float32)
im_[0, ...] = im
starttime = datetime.datetime.now()
predictions = net.forward(data=im_)
endtime = datetime.datetime.now()
print((endtime.microsecond - starttime.microsecond)/1000, "ms")
pred = predictions['prob']
print(pred.argmax())
caffe 自帶的圖像預處理
transformer.set_transpose('data', (2,0,1)) #改變維度的順序,由原始圖片(28,28,3)變爲(3,28,28)
#transformer.set_mean('data', np.load(mean_file).mean(1).mean(1)) #減去均值,前面訓練模型時沒有減均值,這兒就不用
transformer.set_raw_scale('data', 255) # 縮放到【0,255】之間
transformer.set_channel_swap('data', (2,1,0)) #交換通道,將圖片由RGB變爲BGR
參考 denny的學習專欄
NumPy Code
標量函數向量化
import numpy as np
from numpy import vectorize
def r_lookup(x):
return x + 1
r_lookup_vec = vectorize(r_lookup)
a = np.arange(28*28).reshape(28, 28)
b = r_lookup_vec(a)
numpy中axis
在numpy中,.sum(axis=n)解釋:
如果,b是一個shap(5, 6, 7, 8)的numpy array, 然後,c = b.sum(axis=2)
那麼,c的shape將是(5, 6, 8) ,因爲“7”就是axis=2,被清除了。而且,c[x, y, z] = sum( b[x, y, : , z])
from
numpy.unravel_index
給定一個矩陣,求第n個元素在shape下的下標是什麼?矩陣各維的下標從0開始
例如:
print np.unravel_index(100, (6, 7, 8))
(1, 5, 4)
解釋:
給定一個矩陣,shape=(6, 7, 8),即3維的矩陣,求第100個元素的下標。
a = np.arange(15).reshape(3,5)
maxidx = a.argmax() # 最大值的一維位置, 結果爲14
np.unravel_index(maxidx, a.shape) # 最大值在a.shape下的位置,結果爲(2,4)
where
類似於matlab中的find函數
idx = np.where((x > 1) | (x < 0))
dx[idx] = -dx[idx]
常用函數
# -*- coding: utf-8 -*-
'''
保存經常用到的python 函數
'''
import os
import shutil
import random
def list_op():
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(list) # 打亂列表
slice = random.sample(list, 5) # 從list中隨機獲取5個元素,作爲一個片斷返回
return slice
pass
def str2():
# 字符串轉爲元組,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
# 字符串轉爲列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
# 字符串轉爲字典,返回:<type 'dict'>
print type(eval("{'name':'ljq', 'age':24}"))
def genMatrix(rows, cols):
matrix = [[0 for col in range(cols)] for row in range(rows)]
return matrix
def PNG2JPG():
from PIL import Image
img = Image.open("D:\\1.png")
img.save("1.jpeg", format="jpeg")
# 文件操作
def FileOP():
# 目錄操作:
os.mkdir("file")
# 創建目錄
# 複製文件:
shutil.copyfile("oldfile", "newfile") # oldfile和newfile都只能是文件
shutil.copy("oldfile", "newfile") # oldfile只能是文件夾,newfile可以是文件,也可以是目標目錄
# 複製文件夾:
shutil.copytree("olddir", "newdir") # olddir和newdir都只能是目錄,且newdir必須不存在
# 重命名文件(目錄)
os.rename("oldname", "newname")
# 文件或目錄都是使用這條命令
# 移動文件(目錄)
shutil.move("oldpos", "newpos")
# 刪除文件
os.remove("file")
# 刪除目錄
os.rmdir("dir")
# 只能刪除空目錄
shutil.rmtree("dir")
# 空目錄、有內容的目錄都可以刪
# 轉換目錄
os.chdir("path")
# 換路徑
def FunOP():
l = [1, 3, 5, 6, 7, 8]
b = map(lambda a, b: [a, b], l[::2], l[1::2]) # b = [[1,3],[5,6],[7,8]]
return b
pass
def getAllLabelTxt(root_path):
os.system('dir ' + root_path + '\\*.txt /b/s> file_list.txt')
txt = open('file_list.txt', 'r').readlines()
# os.remove('file_list.txt')
return txt
def saveList(man):
try:
man_file=open('man.txt', 'w') # 以w模式訪問文件man.txt
other_file=open('other.txt','w') # 以w模式訪問文件other.txt
print (man, file=man_file) # 將列表man的內容寫到文件中
print (other, file=other_file)
except IOError:
print ('File error')
finally:
man_file.close()
other_file.close()
python版本控制
import sys
if sys.version_info < (3, 4):
raise RuntimeError('At least Python 3.4 is required')