檔案位置關系
filename = 'yourfilename.jpg' #與程式碼相同位置的檔案
filename = './file/yourfilename.jpg' #程式碼資料夾裡的資料夾中的檔案
filename = '../yourfilename.jpg' #程式碼上一層資料夾的檔案
讀取image 及 顯示
import cv2
filename = 'yourfilename.jpg' #與程式碼相同位置的檔案
image = cv2.imread(filename) #讀取照片
cv2.imshow("window title", image) #顯示照片
儲存照片
import cv2
filename = 'yourfilename.jpg' #與程式碼相同位置的檔案
image = cv2.imread(filename) #讀取照片
cv2.imwrite("filename.jpg", image) #儲存照片,試過的檔案格式 .jpg .png
照片尺寸大小取得
image = cv2.imread(filename) #讀取照片
hight = image.shape[1]
width = image.shape[0]
色彩空間轉換
這邊要注意rgb色彩空間在opencv裡排列方式是bgr
image = cv2.imread(filename)
yuv = cv2.cvtColor(image,cv2.COLOR_BGR2YUV) #RGB to YUV
hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV) #RGB to HSV
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #RGB to gray
gray = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR) #gray to rgb
照片三層色分離
import cv2
filename = 'yourfilename.jpg' #與程式碼相同位置的檔案
image = cv2.imread(filename) #讀取照片
yuv = cv2.cvtColor(image,cv2.COLOR_BGR2YUV)
imY, imU, imV = cv2.split(yuv)
cv2.imshow("image Y", imY)
cv2.imshow("image U", imU)
cv2.imshow("image V", imV)
建立水平顯示三張單色圖
import cv2
filename = 'yourfilename.jpg' #與程式碼相同位置的檔案
image = cv2.imread(filename) #讀取照片
yuv = cv2.cvtColor(image,cv2.COLOR_BGR2YUV)
imY, imU, imV = cv2.split(yuv)
three_img = np.zeros((yuv.shape[1],yuv.shape[0]*3), np.uint8) ### 建立畫布
### 將gray圖水平方向拼接
three_img[:,0:width] = imY[:]
three_img[:,width:width*2] = imU[:]
three_img[:,width*2:width*3] = imV[:]
cv2.imshow('three_gray', three_img)
讀影片或webcam
import cv2
class Camera(object):
def __init__(self, camera = 0):
## camera初始設定
self.cam = cv2.VideoCapture(camera)
self.ret = True
if not self.cam:
raise Exception("Camera not accessible.")
def get_frame(self):
## 取得一張frame
frame = None
self.ret, frame = self.cam.read()
return frame
def get_fps(self):
## 取得fps
fps = self.cam.get(cv2.CAP_PROP_FPS)
return fps if fps != -1 else 30.0
def get_size(self):
## 取得frame 的寬高
w = int(self.cam.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(self.cam.get(cv2.CAP_PROP_FRAME_HEIGHT))
return (w,h)
def release_camera(self):
## 結束camera
self.cam.release()
print("release_camera")
return True
def main():
filename = 'yourvideoname.avi' ## 目前試過可讀mp4 avi
cam = Camera(filename) ## 預設0是webcam 輸入filename就讀影片檔
while cam.ret:
frame = cam.get_frame() ## 讀一張frame
if not cam.ret: ## 檢查 video,camera有沒有讀完或斷線
break
cv2.imshow("frame", frame) ## 顯示
key = cv2.waitKey(10) ## 等待??ms ,當值小於等於0 會無限等待,直到按下任意鍵
if (key == 27) | (key == 113): #keyboard:'q' = 113, Esc = 27
# Exit
break
print("close_window")
cam.release_camera() ## 結束camera
cv2.destroyAllWindows() ## 關閉所有window
if __name__=="__main__":
main()
留言
張貼留言