opencv3入門---opencv 1

創建正方形灰度圖像,彩色圖像,分割圖像

import cv2
import numpy as np
import os

# make an array of 120000 random bytes
randomByteArray = bytearray(os.urandom(120000))
flatNumpyArray = np.array(randomByteArray)

# convert the array to make a 400*300 gratscale image
grayImage = flatNumpyArray.reshape(300, 400)
cv2.imwrite("RandomGray.png", grayImage)

# convert the arra to make a 400*100 coloe iamge
bgrImage = flatNumpyArray.reshape(100, 400, 3)
cv2.imwrite("randomColer.png", bgrImage)
#將所有綠色通道設置爲0
bgrImage[:,:,1]=0
cv2.imwrite("random2.png",bgrImage)

#通過numpy索引訪問原始圖像,將第一個區域的值分配給第二個區域
my_roi=grayImage[0:100,0:100]
bgrImage[0:100,0:100]=my_roi
cv2.imwrite("切割.png",bgrImage)

運行

將所有通道綠色通道執爲0的圖像
在這裏插入圖片描述
隨機RGB圖像
在這裏插入圖片描述

視屏文件讀寫

import cv2

videoCapture = cv2.VideoCapture("./video/源視頻0.avi")
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))

videoWriter = cv2.VideoWriter("my_output.avi", cv2.VideoWriter_fourcc('I', '4', '2', '0'),
                              fps, size)

success, frame = videoCapture.read()
while success:
    videoWriter.write(frame)
    success, frame = videoCapture.read()

在這裏插入圖片描述

輸出了avi文件

捕獲攝像頭的幀

import cv2
cameraCapture=cv2.VideoCapture(0)
fps=30
size=(int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
      int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))

videoWrite=cv2.VideoWriter("new.avi",cv2.VideoWriter_fourcc('I','4','2','0'),
                           fps,size)

success,fram=cameraCapture.read()
numframsremaining=10*fps-1
while success  and numframsremaining>0:
    videoWrite.write(fram)
    success,fram=cameraCapture.read()
    numframsremaining-=1

cameraCapture.release()

因爲沒有攝像頭所以沒有結果
在這裏插入圖片描述
生成了文件但是沒有圖像

在窗口顯示圖像,等待一個鍵盤輸入關閉所有圖像

import  cv2
import numpy as np

img=cv2.imread("./randomColer.png")
cv2.imshow('my image',img)
cv2.waitKey()
cv2.destroyAllWindows()

#運行
在這裏插入圖片描述

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