python-opencv及python的常用操作

使一個圖像填充黑色或白色:img[…] = 0或255
變灰度: img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
複製:img_copy = img.copy()
取圖像的長寬通道數:img.shape 即:彩色:rows, cols, channels = img.shape 灰度:rows, cols = img.shape
用標準正太分佈初始化矩陣:mix = np.random.random((3,3))
用一個範圍的整數初始化矩陣:mix = np.random.randint(0,100,size = (3,3))
乘以一個正太分佈數:x = np.random.random()*y
判斷圖像是彩色還是灰度:
if img.ndim == 2#灰度
if img.ndim == 3#彩色

對圖像單個像素進行操作:
灰度:img[y,x] = 255
彩色:
img[y,x,0] = 255
img[y,x,1] = 255
img[y,x,2] = 255

python主函數:if name == ‘main‘:
對通道進行分離:b, g, r = cv2.split(img)
對其中一個通道進行分離: b = cv2.split(img)[0]
對分離後的通道進行顯示: cv2.imshow(‘b’,b)
對分離後的通道進行合併: img_merge = cv2.merge([b,g,r])
創建圖像: img_creat = np.zeros((img.shape[0],img.shape[1]),dtype = img.dtype)或img_creat = np.zeros([500,500,3],np.uint8)其中3爲通道數
把單通道圖像賦給創建好的圖像:img_creat[:,:] = img[:,:,0]或img[:,:,1]或img[:,:,2]
把圖像賦給創建好的圖像:img_creat[:,:,:] = img[:,:,:]
查看numpy的矩陣或向量的數據類型:print arr.dtype
轉換numpy的矩陣或向量的數據類型:arr1 = arr.astype(np.float64)或arr2 = arr1.astype(arr0.dtype)
創建字符串向量/數組:string =np.array([“1”,”3”,”2”,”4”],dtype = np.string_)
創建整型向量/數組: arr = np.array([1,3,4,6])
統計一個圖像上每個像素值的個數:hist = cv2.calcHist([img], [0]#通道, None, [256], [0.0,255.0])
統計一個矩陣元素的最大值、最小值及他們的位置: minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)
對矩陣的每個元素四捨五入:

>>> np.around([0.37, 1.64])
array([ 0.,  2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4,  1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0.,  2.,  2.,  4.,  4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])

創建矩陣:mix = np.arange(4).reshape(2,2)
鏈接兩個向量:

>>> np.hstack([np.array([1, 2, 3]), np.array([4, 5, 6])])
[1, 2, 3, 4, 5, 6]

組合兩個向量:

>>> np.column_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])
[[1, 4]
 [2, 5]
 [3, 6]]

把多個向量祝賀組合變成矩陣:

>>>np.vstack([np.array([1, 2, 3]), np.array([4, 5, 6])])或np.row_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])
[[1, 2, 3]
 [4, 5, 6]]

反轉矩陣:mix = np.flipud(mix) #行的排列順序的顛倒
對數組中的元素縮放到一個指定範圍:cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
畫多邊形:cv2.polylines(img,[pts],False,color)
把數組或矩陣中的全部元素轉換爲整數:hist1 = np.int32(hist)
在某個範圍內取值:for i in range(200,300)
腐蝕:img_eroded = cv2.erode(img,kernel)
膨脹:img_dilated = cv2.dilate(img,kernel)
對腐蝕或膨脹中kernel的定義:kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
開運算:先腐蝕後膨脹————閉運算相反
開運算:img_opened = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) #其中kernel與腐蝕與膨脹的定義一樣
閉運算:img_closed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
邊緣檢測的一種方法:膨脹-腐蝕
兩圖像相減:img_result = cv2.absdiff(img_dilated, img_eroded)
二值化: reVal, img_result = cv2.threshold(img_result, 40, 255, cv2.THRESH_BINARY) #其中result爲所求對象
對像素值取反:img_result_over = cv2.bitwise_not(img_result)
在圖像上畫圓:cv2.circle(img,(j,i),10,(255,0,0))
blur濾波(取每個像素周圍像素的均值):dst = cv2.blur(img, (5, 5))等效於dst = cv2.boxFilter(img, -1, (5, 5))
高斯模糊:dst = cv2.GaussianBlur(img, (5,5), 1.5)
中值濾波(可消除椒鹽):dst = cv2.medianBlur(img, 5)
Resize圖片的大小:
dst = cv2.resize(img, (img1.shape[0], img1.shape[1]))
放大或縮小原圖:dst = cv2.resize(img,None,fx=2,fy=2)

兩張尺寸一樣的圖片疊加:img_overlay = cv2.addWeighted(img1, 0.6, img2, 0.4, 0)
把數組或矩陣中的元素轉化爲8位無符號整型:dst = cv2.convertScaleAbs(src)
讀取視頻:capture = cv2.VideoCapture(video)
讀取視頻的每幀:
while 1:
ret, img = capture.read()
cv2.imshow(‘video’, img)
if cv2.waitKey(20) & 0xFF == ord(‘q’):
break
capture.release()
cv2.destroyAllWindows()

輸出十六進制:print(‘%x’%key)
把字符轉成ascii碼:val = ord(‘q’)
把ascii碼轉成字符:char = chr(65)
sobel算子(一種帶有方向的過濾器):x = cv2.Sobel(img,cv2.CV_16S,1,0) 或x = cv2.Sobel(img,cv2.CV_16S,0,1)
在一張圖像上選擇一片區域貼另一張圖:
from PIL import Image
img_base = Image.open(‘/home/jc/桌面/opencv練習/53.jpg’)
img_ps = Image.open(‘/home/jc/桌面/opencv練習/未標題-3.jpg’)
img_base.paste(img_ps, box)其中box = (300, 64, 300+rows, 64+cols)
img_base.show()
base_img.save(‘/home/jc/桌面/opencv練習/h.jpg’)

輸出一張圖片的大小:print img.size
Laplacian算子:dst = cv2.Laplacian(img, cv2.CV_16S, ksize = 3)
Canny邊緣檢測算子: canny = cv2.Canny(img1, 50, 150) 先對原圖片進行高斯模糊得到img1
把數字轉化爲字符:x = str(4)
刪除數組中指定元素:list.remove(元素)
刪除數組中指定下標的元素:del list[i]
刪除列表最後一個元素:list.pop()
在數組中追加元素:x.append(元素)
在兩個數之間遍歷:for i in range(x1, x2):
在圖像上畫矩形:cv2.rectangle(img, (x0,x1), (x2, x3), (255,0,0), 3)
對小數取整:x1 = int(x0)
對取文件中所有行組成一個列表:
f = open(path,’r’)
lines = f.readlines()

對文件進行寫操作並覆蓋原文件中的數據:f = open(path, ‘w’)
把列表中的信息寫入一個文件中(每個元素一行):
f = open(path, ‘w+’) #若文件不存在,則自動創建
f.writelines(lines)
長寬在函數中的位置:
img = np.zeros([y,x,3], dtype = np.uint8) #其中x爲圖像橫座標的長度
img1[y, x, 0] = img[y, x, 0] #x爲圖像橫座標的長度
print img.shape—>(y,x,3) #x爲圖像橫座標的長度
cv2.line(img, (x0, y0), (x1, y1), (255, 0, 0)) #x0爲圖像橫座標
處理視頻時,opencv只支持avi,生成的視頻不能大於2G,且不能添加音頻。
把多張圖片製作成視頻:
savefile = ‘/home/jc/圖片/hi.avi’
fourcc = cv2.VideoWriter_fourcc(‘M’, ‘J’, ‘P’, ‘G’)
fps = 5
out = cv2.VideoWriter(savefile, fourcc, fps, (img.clos, img.rows))
for root, dirs, files in os.walk(path)
for file in files:
file_path = os.path.join(path,file)
img = os.imread(file_path)
out.write(img)
cv2.waitKey(1)

讀取視頻幀,寫入視頻:
savefile = ‘/home/jc/圖片/hi.avi’
fourcc = cv2.VideoWriter_fourcc(‘M’, ‘J’, ‘P’, ‘G’)
fps = 5
out = cv2.VideoWriter(savefile, fourcc, fps, (img.clos, img.rows))
video = (‘/home/jc/視頻/Wildlife.avi’)
capture=cv2.VideoCapture(video)
while 1:
ret, img=capture.read()
out.write(img)
cv2.waitKey(1)

腐蝕或膨脹時使用橢圓kernel會使圖像平滑:kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
動態創建變量:
createVar = locals()
for c in range(30):
createVar[‘img_ccopy’ + str(c)] = np.zeros([567, 567, 3], np.uint8)

複製文件:shutil.copyfile(‘oldfile’, ‘newfile’) #oldfile和newfile只能是文件
複製一個文件夾中的內容到另一個文件夾: shutil.copy(‘oldfile’, ‘newdir’)
移動文件:shutil.move(‘oldfile_path’, ‘newfile_path’)
刪掉文件夾及其中的全部內容:shutil.rmtree(path)
僅能刪掉空目錄:os.rmdir(path)
判斷文件或文件夾是否存在:os.path.exists(path)
判斷是否爲文件夾:os.path.isdir(path)
判斷是否爲文件:os.path.isfile(path)
對字符串進行兩次分割:
string = “www.gziscas.com.cn”
print(string.split(‘.’,2)) –> [‘www’, ‘gziscas’, ‘com.cn’]

u1, u2, u3 =string.split(‘.’,2)
print(u1) –> www
print(u2) –> gziscas
print(u3) –> com.cn

分離路徑與文件名:os.path.split(path)
計時函數(單位:秒):
start = time.time()
函數體
end = time.time()
print end - start

隨機在取文件夾中的文件或文件夾:
for root, dirs, files in os.walk(path)
c = len(dirs)
break
path_dir = os.path.join(path, dirs[np.random.randint(0, c)])

按列表中元素的某種元素進行排序:
L = [(‘b’,2),(‘e’,1),(‘c’,3),(‘d’,4)]
L.sort(key=lambda x:x[1]) #若降序排列,則:L.sort(key=lambda x:x[1], reverse=True)
print L –> [(‘e’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)]

遞歸創建目錄:
os.makedirs(path)
動態變量:
creatVar = lacals()
for i in range(11):
creatVar[‘color’ + str(i8)] = np.zeros([567, 567, 3], np.uint8)

creatSub = lacals()
for i in range(11):
creatSub[‘color1’ + str(i)] = 0
其中creatVar[‘color’ + str(10)]與creatSub[‘color1’ + str(0)]變量名相同,發生衝突

輸出某一元素在列表中的位置:
l = [‘d’, ‘a’, 1, 3, 55, 24, 53]
print l.index(‘a’)

format的用法:
print ‘{:,}’.format(1234567893444)–>1,234,567,893,444
print ‘{:x}’.format(123)–>7b
print ‘{0},{1}’.format(‘hello’, 24)–>hello,24
print ‘{},{}’.format(‘hello’, 24)–>hello,24
print ‘{name},{age}’.format(name = ‘jc’, age = 24)–>jc,24
print ‘{:>8}’.format(1234)–> 1234
print ‘{:a>8}’.format(1234)–>aaaa1234
print ‘{:.2f}’.format(1234.435525)–>1234.44

glob.glob()的用法(尋找滿足條件的所有文件):
for i in glob.glob(‘/home/jc/圖片/test//.jpg’):
img = cv2.imread(i)

寫xml文件時,座標的格式一定是整型而非字符,否則可以訓練單不能識別。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章