1. Giải thích mã nguồn
Viết chương trình bằng Python sử dụng thư viện imageio kết hợp ffmpeg để xử lý video có định dạng nén HVC1/H.265. Chương trình hỗ trợ:
- Tự động trích xuất khung hình từ tất cả video trong một thư mục
- Tùy chỉnh tần suất trích xuất (số khung hình/ giây)
- Tạo tên tập tin đầu ra theo quy tắc tùy chỉnh
2. Cấu trúc đầu ra mẫu
E:/FAST-data/Pic/
├── DJI_20250429_0001_S/
│ ├── frame_000000.jpg
│ ├── frame_000030.jpg
│ └── ...
├── DJI_20250429_0002_S/
│ ├── ...
3. Quy trình thực hiện
3.1 Cài đặt phụ thuộc
python -m pip install imageio[ffmpeg]
3.2 Cấu hình tham số
Điều chỉnh đường dẫn đầu vào/thoát và tần số trích xuất:
duong_dan_vao = r"Đường dẫn thư mục chứa video"
duong_dan_ra = r"Đường dẫn thư mục lưu trữ"
tang_tu_do_khung_hinh = 2 # Số khung hình trích xuất mỗi giây
Tùy chỉnh tên tập tin đầu ra:
ten_tap_tin = f"{duong_dan_ra[-6:-1]}{i:06d}_{duong_dan_ra[-1:]}.jpg"
- Mã nguồn hoàn chỉnh
import os
import imageio.v3 as iio
def trich_xuat_khung_hinh(ten_video, duong_dan_thoat, tang_tu_do=1):
try:
thong_tin = iio.immeta(ten_video)
tien_do = thong_tin.get("fps", 30)
except Exception as e:
print(f"❌ Lỗi đọc thông tin: {ten_video}, nguyên nhân: {e}")
return
khoang_cach = round(tien_do / tang_tu_do)
print(f"🎞️ Đang xử lý: {ten_video}")
print(f" Tần số khung hình: {tien_do:.2f}, trích xuất mỗi {khoang_cach} khung hình")
os.makedirs(duong_dan_thoat, exist_ok=True)
try:
for i, khung_hinh in enumerate(iio.imiter(ten_video)):
if i % khoang_cach == 0:
ten_tap_tin = f"{duong_dan_thoat[-6:-1]}{i:06d}_{duong_dan_thoat[-1:]}.jpg"
duong_dan_luu = os.path.join(duong_dan_thoat, ten_tap_tin)
iio.imwrite(duong_dan_luu, khung_hinh)
print(f" ✅ Lưu trữ: {duong_dan_luu}")
except Exception as e:
print(f"❌ Lỗi trong quá trình trích xuất: {ten_video}, nguyên nhân: {e}")
return
print(f"✅ Hoàn tất: {ten_video}\n")
def xu_ly_tat_ca_video(duong_dan_vao, duong_dan_ra, tang_tu_do=1):
ket_noi_ho_tro = ('.mp4', '.mkv', '.mov', '.avi')
for ten_file in os.listdir(duong_dan_vao):
if ten_file.lower().endswith(ket_noi_ho_tro):
duong_dan_video = os.path.join(duong_dan_vao, ten_file)
ten_chinh = os.path.splitext(ten_file)[0]
duong_dan_luu = os.path.join(duong_dan_ra, ten_chinh)
trich_xuat_khung_hinh(duong_dan_video, duong_dan_luu, tang_tu_do)
if __name__ == "__main__":
duong_dan_vao = r"E:\FAST-data\Video"
duong_dan_ra = r"E:\FAST-data\Pic"
tang_tu_do = 2 # Số khung hình trích xuất mỗi giây
xu_ly_tat_ca_video(duong_dan_vao, duong_dan_ra, tang_tu_do)