정보통신기술(ICT)

맵 타임랩스 소프트웨어

해머슴 2024. 10. 28. 10:07
import sys
import cv2
import numpy as np
import os
import subprocess
import platform
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QFileDialog, QLabel
from PyQt5.QtCore import Qt

def apply_shading(image, alpha=1.0, beta=50):
    shaded_image = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
    return shaded_image

def create_video_with_shading(image_files, video_path, width, height, total_duration=10):
    fps = 30
    total_frames = int(total_duration * fps)
    num_images = len(image_files)
    frames_per_image = total_frames // num_images
    transition_frames = frames_per_image // 2

    video = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'XVID'), fps, (width, height))

    print(f"Total frames for the video: {total_frames}")
    print(f"Frames per image (including transition): {frames_per_image}")
    print(f"Transition frames between images: {transition_frames}")

    total_written_frames = 0

    for i in range(num_images - 1):
        img1 = cv2.imread(image_files[i])
        img2 = cv2.imread(image_files[i + 1])
       
        if img1 is None:
            print(f"Warning: Could not load image {image_files[i]}. Skipping this image.")
            continue
        if img2 is None:
            print(f"Warning: Could not load image {image_files[i + 1]}. Skipping this image.")
            continue
       
        img1 = cv2.resize(img1, (width, height))
        img2 = cv2.resize(img2, (width, height))
       
        shaded_img1 = apply_shading(img1, alpha=1.2, beta=30)
        shaded_img2 = apply_shading(img2, alpha=1.2, beta=30)
       
        # 이미지 유지 프레임 (트랜지션 없이)
        for _ in range(frames_per_image - transition_frames):
            frame_with_text = add_frame_number(shaded_img1, total_written_frames)
            video.write(frame_with_text)
            total_written_frames += 1
       
        # 트랜지션 프레임 (페이드 인/아웃 효과)
        for alpha in np.linspace(0, 1, transition_frames):
            blended = cv2.addWeighted(shaded_img1, 1 - alpha, shaded_img2, alpha, 0)
            frame_with_text = add_frame_number(blended, total_written_frames)
            video.write(frame_with_text)
            total_written_frames += 1
   
    # 마지막 이미지 처리
    last_image = cv2.imread(image_files[-1])
    if last_image is not None:
        last_image = cv2.resize(last_image, (width, height))
        shaded_last_image = apply_shading(last_image, alpha=1.2, beta=30)
       
        # 마지막 이미지 유지 프레임
        for _ in range(frames_per_image):
            frame_with_text = add_frame_number(shaded_last_image, total_written_frames)
            video.write(frame_with_text)
            total_written_frames += 1
   
    video.release()
    print(f"Video saved to {os.path.abspath(video_path)}")
    print(f"Total frames written: {total_written_frames}")

def add_frame_number(image, frame_number):
    """
    이미지에 프레임 번호를 추가하는 함수.
    """
    font = cv2.FONT_HERSHEY_SIMPLEX
    text = f"Frame: {frame_number}"
    font_scale = 1
    color = (0, 255, 0)
    thickness = 2
    position = (50, 50)

    # 이미지에 텍스트 추가
    frame_with_text = cv2.putText(image.copy(), text, position, font, font_scale, color, thickness, cv2.LINE_AA)
    return frame_with_text

def play_video(video_path):
    try:
        if platform.system() == "Windows":
            os.startfile(video_path)
        elif platform.system() == "Darwin":
            subprocess.call(["open", video_path])
        else:
            subprocess.call(["xdg-open", video_path])
    except Exception as e:
        print(f"Failed to play the video: {e}")

class SatelliteMapVideoApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Satellite Map Video Generator")
        self.setGeometry(100, 100, 800, 600)
       
        layout = QVBoxLayout()
        self.label = QLabel("Select images and create video", self)
        self.label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label)
       
        self.select_button = QPushButton("Select Images", self)
        self.select_button.clicked.connect(self.select_images)
        layout.addWidget(self.select_button)
       
        self.create_button = QPushButton("Create Video", self)
        self.create_button.clicked.connect(self.create_video)
        layout.addWidget(self.create_button)
       
        self.setLayout(layout)
        self.images = []

    def select_images(self):
        files, _ = QFileDialog.getOpenFileNames(self, "Select Image Files", "", "Images (*.png *.jpg *.jpeg *.bmp)")
        if files:
            self.images = files
            self.label.setText(f"{len(files)} images selected.")

    def create_video(self):
        if not self.images:
            self.label.setText("No images selected.")
            return
       
        video_path, _ = QFileDialog.getSaveFileName(self, "Save Video As", "", "Video Files (*.avi)")
        if not video_path:
            self.label.setText("Video creation canceled.")
            return
       
        create_video_with_shading(self.images, video_path, 640, 480, total_duration=10)
        self.label.setText(f"Video saved to {video_path}")
        play_video(video_path)

def main():
    app = QApplication(sys.argv)
    window = SatelliteMapVideoApp()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

 

 

https://www.tistory.com/event/write-challenge-2024

 

작심삼주 오블완 챌린지

오늘 블로그 완료! 21일 동안 매일 블로그에 글 쓰고 글력을 키워보세요.

www.tistory.com