# Video python snippets

## Generate 20 captions

```python
import requests
import json

X_RapidAPI_Key = '4116843d07msh704be0dfa337826p108b3fj43524'
X_RapidAPI_Host = 'colorize-video.p.rapidapi.com'

headers = {
    'X-RapidAPI-Key': '4116843d07msh704be0dfa337826p108b3fjsn7ab402961f9f',
    'X-RapidAPI-Host': 'colorize-video.p.rapidapi.com',
}

url = "https://" + X_RapidAPI_Host + "/generate_video_frame_prompt"

files = {
    'image': ('test.jpg', open('./test.jpg', 'rb'), 'image/jpeg')   
}

data = {
  "standard_filter_id": "0", # 1-20, 0 is disabled 
  "artistic_filter_id": "0", # 1-100, 0 is disabled
  "all_standard_filters": "true", # return all 20 prompts
  "all_artistic_filters": "false", # return all 100 prompts
  "raw_captions": "false" # remove pre and post fix to the caption
}

response = requests.post(url, files=files, data=data, headers=headers)
prompts = data = json.loads(response.text)
```

## Create 20 versions of one frame

```python
import requests

X_RapidAPI_Key = '4116843d07msh704be0dfa337826p108b3fj43524'
X_RapidAPI_Host = 'colorize-video.p.rapidapi.com'

headers = {
    'X-RapidAPI-Key': '4116843d07msh704be0dfa337826p108b3fjsn7ab402961f9f',
    'X-RapidAPI-Host': 'colorize-video.p.rapidapi.com',
}

url = "https://" + X_RapidAPI_Host + "/colorize_video_frame_with_prompt"

data = {
      "resolution": "sd", #sd, full-hd, or 4k
      "prompt": "", # The prompt to colorize an image
      "auto_color": "false", # Apply automatic color balancing
      "white_balance": "false", # Apply automatic white balancing
      "temperature": "0.0", # -1.0 - 1.0, Apply color temperature
      "saturation": "1.0" # 0.0 - 2.0, Change saturation 
    }

for i, prompt in enumerate(prompts):
    
    files = {
        'image': ('test.jpg', open('./test.jpg', 'rb'), 'image/jpeg')   
    }

    data['prompt'] = prompt

    response = requests.post(url, files=files, data=data, headers=headers)
    f = open(str(i) + ".jpg", 'wb')
    f.write(response.content)
    f.close()
```

## Extract all the frames from a video

```python
import cv2
import os

def extract_images_from_video(video_path, output_folder):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Open the video file
    video = cv2.VideoCapture(video_path)

    # Check if the video was opened successfully
    if not video.isOpened():
        print("Error: Could not open the video file.")
        return

    # Extract images from the video
    frame_number = 0
    while True:
        ret, frame = video.read()

        # Break the loop if we have reached the end of the video
        if not ret:
            break

        # Save the current frame as an image
        output_filename = os.path.join(output_folder, f"frame{frame_number}.png")
        cv2.imwrite(output_filename, frame)
        frame_number += 1

    # Release the video object and close all windows
    video.release()
    cv2.destroyAllWindows()
    print(f"Images extracted and saved in the folder: {output_folder}")
```

## Colorize all the frames with the same prompt

```python
import os
import time
import requests

X_RapidAPI_Key = '4116843d07msh704be0dfa337826p108b3fj43524'
X_RapidAPI_Host = 'colorize-video.p.rapidapi.com'

headers = {
    'X-RapidAPI-Key': '4116843d07msh704be0dfa337826p108b3fjsn7ab402961f9f',
    'X-RapidAPI-Host': 'colorize-video.p.rapidapi.com',
}

def colorize_image(input_file, output_file, prompt):
  
    url = "https://" + X_RapidAPI_Host + "/colorize_video_frame_with_prompt"
    
    files = {
        'image': (input_file, open(input_file, 'rb'), 'image/jpeg')
    }
    data = {
        "resolution": "sd",
        "prompt": prompt,
        "auto_color": "false",
        "white_balance": "false",
        "temperature": "0.0",
        "saturation": "1.0"
    }
    response = requests.post(url, files=files, data=data, headers=headers)
    
    with open(output_file, 'wb') as f:
        f.write(response.content)

def process_files(input_folder, output_folder, prompt):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for filename in os.listdir(input_folder):
        input_file = os.path.join(input_folder, filename)
        output_file = os.path.join(output_folder, f'colorized_{filename}')
        success = False
        retries = 0

        while not success and retries < 10:
            try:
                colorize_image(input_file, output_file, prompt)
                success = True
            except Exception as e:
                print(f"Error processing {input_file}: {e}")
                time.sleep(60)
                retries += 1

input_folder = './input'
output_folder = './output'
prompt = "Your selected prompt"
process_files(input_folder, output_folder, prompt)

```

## Colorize all the images with the same reference image

```python
import os
import time
import requests
from pathlib import Path

X_RapidAPI_Key = '4116843d07msh704be0dfa337826p108b3fj43524'
X_RapidAPI_Host = 'colorize-video.p.rapidapi.com'

headers = {
    'X-RapidAPI-Key': '4116843d07msh704be0dfa337826p108b3fjsn7ab402961f9f',
    'X-RapidAPI-Host': 'colorize-video.p.rapidapi.com',
}

def colorize_files(input_folder, output_folder, ref_image_path):
    
    url = "https://" + X_RapidAPI_Host + "/colorize_video_frame_with_prompt"
   
    data = {
        "resolution": "sd",
        "auto_color": "false",
        "white_balance": "false",
        "temperature": "0.0",
        "saturation": "1.0"
    }
    
    Path(output_folder).mkdir(parents=True, exist_ok=True)
    
    for file_name in os.listdir(input_folder):
        if file_name.lower().endswith(('.jpg', '.jpeg')):
            input_file_path = os.path.join(input_folder, file_name)
            output_file_path = os.path.join(output_folder, f'colorized_{file_name}')
            
            for _ in range(10):
                try:
                    files = {
                        'image': (file_name, open(input_file_path, 'rb'), 'image/jpeg'),
                        'image_ref': ('ref_image.jpg', open(ref_image_path, 'rb'), 'image/jpeg')
                    }
                    response = requests.post(url, files=files, data=data, headers=headers)
                    response.raise_for_status()
                    
                    with open(output_file_path, 'wb') as f:
                        f.write(response.content)
                    
                    print(f"Colorized {file_name} and saved as {output_file_path}")
                    break
                except Exception as e:
                    print(f"Error while processing {file_name}: {e}")
                    time.sleep(60)

input_folder = './input_folder'
output_folder = './output_folder'
ref_image_path = 'ref_image.jpg'

colorize_files(input_folder, output_folder, ref_image_path)

```

## Use the previous frame to colorize one after each other

```python
import os
import time
import requests
from pathlib import Path

X_RapidAPI_Key = '4116843d07msh704be0dfa337826p108b3fj43524'
X_RapidAPI_Host = 'colorize-video.p.rapidapi.com'

headers = {
    'X-RapidAPI-Key': '4116843d07msh704be0dfa337826p108b3fjsn7ab402961f9f',
    'X-RapidAPI-Host': 'colorize-video.p.rapidapi.com',
}

def colorize_images(folder_path):
    
    url = "https://" + X_RapidAPI_Host + "/colorize_video_frame_with_prompt"
   
    data = {
        "resolution": "sd",
        "auto_color": "false",
        "white_balance": "false",
        "temperature": "0.0",
        "saturation": "1.0"
    }
    
    output_folder = Path(folder_path) / "colorized"
    output_folder.mkdir(parents=True, exist_ok=True)

    reference_image = Path(folder_path) / "the_first_reference.jpg"

    for file in os.listdir(folder_path):
        if file.endswith(".jpg") or file.endswith(".jpeg"):
            input_file = Path(folder_path) / file

            retries = 10
            while retries > 0:
                try:
                    files = {
                        'image': (file, open(input_file, 'rb'), 'image/jpeg'),
                        'image_ref': ('ref_image.jpg', open(reference_image, 'rb'), 'image/jpeg')
                    }

                    response = requests.post(url, files=files, data=data, headers=headers)
                    response.raise_for_status()

                    colorized_file = output_folder / f'colorized_{file}'
                    with open(colorized_file, 'wb') as f:
                        f.write(response.content)

                    reference_image = colorized_file
                    break

                except requests.exceptions.RequestException:
                    retries -= 1
                    time.sleep(60)
                    
colorize_images("path/to/your/folder")

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.palette.fm/video-processing/video-python-snippets.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
