การเปิดภาพ:
ในหัวข้อนี้จะเป็นการแนะนำการเปิดภาพแบบต่างๆ เช่น การเปิดภาพจากไฟล์ภาพ .jpg หรือ .png การอ่านภาพเคลื่อนไหวจากกล้อง การอ่านไฟล์ภาพเคลื่อนไหวจากไฟล์วีดี .mp4 มีรายละเอียดดังต่อไนี้
1. การเปิดภาพจากไฟล์ภาพ .jpg หรือ .png (สามารถเข้าไปดาวน์โหลดไฟล์ภาพได้จาก >> คลิกเพื่อดาวน์โหลด)
import cv2
img = cv2.imread(r'C:\Users\user\Desktop\bottle\1.jpg')
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. การเปิดภาพจากไฟล์ภาพเคลื่อนไหวจากไฟล์วีดี .mp4 (สามารถเข้าไปดาวน์โหลดไฟล์ภาพได้จาก >> คลิกเพื่อดาวน์โหลด)
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(r'C:\Users\user\Desktop\bean_vdo.mp4')
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
cv.imshow('vdo', frame)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
3. การเปิดทุกภาพจากโฟลเดอร์ที่กำหนด (สามารถเข้าไปดาวน์โหลดไฟล์ภาพได้จาก >> คลิกเพื่อดาวน์โหลด)
import cv2
import glob
path = r'C:\Users\user\Desktop\bottle\*.*'
for file in glob.glob(path):
print(file)
img = cv2.imread(file)
cv2.imshow('Color image',img)
cv2.waitKey(2000)
cv2.destroyAllWindows()
4. การเปิดภาพจากไฟล์ภาพเคลื่อนไหวจากกล้อง
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
cv.imshow('vdo', frame)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
การบันทึกภาพ:
ในหัวข้อนี้จะเป็นการแนะนำการบันทึกภาพแบบต่างๆ เช่น การบันทึกภาพจากกล้องเป็นไฟล์ภาพ .jpg หรือ .png การบันทึกภาพเคลื่อนไหวจากกล้องเป็นไฟล์วีดี .mp4 มีรายละเอียดดังต่อไนี้
1. การบันภาพจากกล้องเป็นไฟล์ภาพ .jpg หรือ .png
import cv2
img = cv2.imread(r'C:\Users\user\Desktop\bottle\1.jpg')
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. การบันภาพเคลื่อนไหวจากกล้องบันทึกเป็นไฟล์วีดีโอ .mp4
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter(r'C:\Users\user\Desktop\vdo.mp4', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
frame = cv.flip(frame, 0)
# write the flipped frame
out.write(frame)
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()