Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

2/02/2025

Find and search which webcam is online on your computer.

 python code:


.

import cv2
import time

def check_cameras():
print("\nChecking camera indices 0-9...")
print("----------------------------------------")
working_cameras = []
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
# Try to read a frame
ret, frame = cap.read()
if ret:
# Get camera properties
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
# Get backend info
backend = cap.getBackendName()
print(f"\n✓ Camera {i} is ONLINE:")
print(f" Resolution: {width}x{height}")
print(f" FPS: {fps}")
print(f" Backend: {backend}")
print(f" Frame shape: {frame.shape}")
# Try to get more detailed format information
fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
fourcc_str = "".join([chr((fourcc >> 8 * i) & 0xFF) for i in range(4)])
print(f" Format: {fourcc_str}")
working_cameras.append(i)
# Test a few more frames to ensure stability
frames_to_test = 5
success_count = 0
for _ in range(frames_to_test):
ret, frame = cap.read()
if ret:
success_count += 1
time.sleep(0.1)
print(f" Stability test: {success_count}/{frames_to_test} frames captured successfully")
else:
print(f"✗ Camera {i}: Device found but cannot read frames")
cap.release()
else:
print(f"✗ Camera {i}: Not available")
print("\n----------------------------------------")
print("Summary:")
if working_cameras:
print(f"Working camera indices: {working_cameras}")
else:
print("No working cameras found")
print("----------------------------------------")

def main():
print("Starting camera detection...")
check_cameras()
print("\nCamera check complete!")

if __name__ == "__main__":
main()

..



output is looks like:

Starting camera detection...


Checking camera indices 0-9...

----------------------------------------


✓ Camera 0 is ONLINE:

  Resolution: 640x480

  FPS: 30.0

  Backend: V4L2

  Frame shape: (480, 640, 3)

  Format: YUYV

  Stability test: 5/5 frames captured successfully

[ WARN:0@0.913] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video1): can't open camera by index

[ERROR:0@0.972] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 1: Not available


✓ Camera 2 is ONLINE:

  Resolution: 640x480

  FPS: 30.0

  Backend: V4L2

  Frame shape: (480, 640, 3)

  Format: YUYV

  Stability test: 5/5 frames captured successfully

[ WARN:0@1.818] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video3): can't open camera by index

[ERROR:0@1.820] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 3: Not available

[ WARN:0@1.820] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video4): can't open camera by index

[ERROR:0@1.822] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 4: Not available

[ WARN:0@1.822] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video5): can't open camera by index

[ERROR:0@1.823] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 5: Not available

[ WARN:0@1.824] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video6): can't open camera by index

[ERROR:0@1.825] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 6: Not available

[ WARN:0@1.825] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video7): can't open camera by index

[ERROR:0@1.828] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 7: Not available

[ WARN:0@1.828] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video8): can't open camera by index

[ERROR:0@1.830] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 8: Not available

[ WARN:0@1.830] global cap_v4l.cpp:999 open VIDEOIO(V4L2:/dev/video9): can't open camera by index

[ERROR:0@1.831] global obsensor_uvc_stream_channel.cpp:158 getStreamChannelGroup Camera index out of range

✗ Camera 9: Not available


----------------------------------------

Summary:

Working camera indices: [0, 2]

----------------------------------------


Camera check complete!



so you can know which one is online


Thank you!


9/22/2024

What is TorchOps.cpp.inc in torch-mlir

 

What is TorchOps.cpp.inc?

  • TorchOps.cpp.inc: This file contains implementations of the operations for the torch-mlir dialect. It is typically generated from .td (TableGen) files that define the dialect and its operations.
  • The .td (TableGen) files describe MLIR operations in a high-level, declarative form, and the cmake build process automatically generates .cpp.inc files (like TorchOps.cpp.inc) from these .td files.

How it gets generated:

  1. TableGen: The TableGen tool processes .td files that define the operations and attributes for the torch dialect.
  2. CMake Build: During the CMake build process, the mlir-tblgen tool is invoked to generate various .inc files, including TorchOps.cpp.inc.

Where It Is Generated:

The TorchOps.cpp.inc file is usually generated in the build directory under the subdirectories for the torch-mlir project. For example:


build/tools/torch-mlir/lib/Dialect/Torch/IR/TorchOps.cpp.inc

This file gets included in the compiled source code to provide the implementation of the Torch dialect operations.

How to Ensure It Is Generated:

If the file is missing, it's likely because there was an issue in the build process. Here’s how to ensure it’s generated:

  1. Ensure CMake and Ninja Build: Make sure the CMake and Ninja build process is working correctly by following the steps we discussed earlier. You can check that the TorchOps.cpp.inc file is generated by looking in the build directory:

    ls build/tools/torch-mlir/lib/Dialect/Torch/IR/
  2. Check for TableGen Files: Make sure that the .td files (such as TorchOps.td) are present in the source directory. These are used by mlir-tblgen to generate the .cpp.inc files.

Debugging if Not Generated:

If TorchOps.cpp.inc or similar files are not generated, ensure:

  • You are running the full build using ninja or make.
  • mlir-tblgen is being invoked during the build process (you should see log messages referencing mlir-tblgen).

IREE test code and explanation

.

from iree import compiler, runtime
import numpy as np
import sys

def print_step(step):
print(f'Step: {step}', file=sys.stderr)

# MLIR code as a string
module_str = '''
func.func @simple_add(%arg0: tensor<4xf32>, %arg1: tensor<4xf32>) -> tensor<4xf32> {
%0 = arith.addf %arg0, %arg1 : tensor<4xf32>
return %0 : tensor<4xf32>
}
'''

print_step('Compiling module')
compiled_module = compiler.compile_str(module_str, target_backends=['llvm-cpu'])

print_step('Creating runtime config')
config = runtime.Config('local-task')

print_step('Creating system context')
ctx = runtime.SystemContext(config=config)

print_step('Creating VM instance')
vm_instance = runtime.VmInstance()

print_step('Creating VM module')
vm_module = runtime.VmModule.from_flatbuffer(vm_instance, compiled_module, warn_if_copy=False)

print_step('Adding VM module to context')
ctx.add_vm_module(vm_module)

print_step('Getting device')
device = runtime.get_driver('local-task').create_default_device()
print(f'Device: {device}', file=sys.stderr)

print_step('Getting function')
f = ctx.modules.module.simple_add

print_step('Creating device arrays')
arg1 = runtime.asdevicearray(device, np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32))
arg2 = runtime.asdevicearray(device, np.array([5.0, 6.0, 7.0, 8.0], dtype=np.float32))

print_step('Calling function')
result = f(arg1, arg2)

print_step('Getting result')
print(result.to_host())

print_step('Script completed successfully')

..

To run this code:

  1. Save it to a file, e.g., test_iree.py.
  2. Make sure you have IREE and its Python bindings installed and properly set up in your environment.
  3. Run the script using Python:
    python test_iree.py

This script will:

  1. Define a simple MLIR function that adds two 4-element float32 tensors.
  2. Compile this MLIR code to an IREE module.
  3. Set up the IREE runtime environment.
  4. Create input data as NumPy arrays.
  5. Execute the compiled function with the input data.
  6. Print the result.

The output should show each step of the process and finally print the result, which should be [ 6. 8. 10. 12.].

This example demonstrates the basic workflow for testing MLIR code with IREE using Python. You can modify the MLIR code string and input data to test different functions and operations as needed.



6/04/2024

Embedding invisible water mark on image

 Firstly, install opencv

pip install opencv-python numpy


code for invisible water mark embedding 

import cv2
import numpy as np

def embed_watermark(image_path, watermark, output_path):
# Load the image
img = cv2.imread(image_path)
# Ensure the image is in 3 channels RGB
if img.shape[2] != 3:
print("Image needs to be RGB")
return
# Prepare the watermark
# For simplicity, the watermark is repeated to match the image size
watermark = (watermark * (img.size // len(watermark) + 1))[:img.size]
watermark = np.array(list(watermark), dtype=np.uint8).reshape(img.shape)
# Embed watermark by altering the least significant bit
img_encoded = img & ~1 | (watermark & 1)
# Save the watermarked image
cv2.imwrite(output_path, img_encoded)
print("Watermarked image saved to", output_path)

# Usage
embed_watermark('path_to_your_image.jpg', 'your_watermark_text', 'watermarked_image.jpg')


retrive code

def extract_watermark(watermarked_image_path, original_image_path, output_path):
# Load the watermarked and the original image
img_encoded = cv2.imread(watermarked_image_path)
img_original = cv2.imread(original_image_path)

# Extract the watermark by comparing the least significant bits
watermark = img_encoded & 1 ^ img_original & 1
watermark = (watermark * 255).astype(np.uint8) # Scale to 0-255 for visibility

# Save or display the extracted watermark
cv2.imwrite(output_path, watermark)
print("Extracted watermark saved to", output_path)

# Usage
extract_watermark('watermarked_image.jpg', 'path_to_your_image.jpg', 'extracted_watermark.jpg')

2/26/2024

Dominant frequency extraction.

 



Let's say we have channel x Length signal data ex)EEG (electroencephalogram) or time series data.

We might wonder what dominant Hz is there.

The code analysis this question and return 5 top dominant frequency. 

.

import numpy as np
from collections import Counter
from scipy.signal import welch

def identify_dominant_frequencies(signal, fs, top_n=5):
freqs, psd = welch(signal, fs)
peak_indices = np.argsort(psd)[-top_n:]
dominant_freqs = freqs[peak_indices]
return dominant_freqs

..
dominant_freqs = identify_dominant_frequencies(signal, fs, top_n)
dominant_freqs_summary[channel].extend(dominant_freqs) # Append the frequencies
..
median_dominant_freqs = {channel: np.median(freqs) if freqs else None for channel, freqs in dominant_freqs_summary.items()}
..

def get_top_n_frequencies(freq_list, top_n=5, bin_width=1.0):
# Bin frequencies into discrete intervals
binned_freqs = np.round(np.array(freq_list) / bin_width) * bin_width
# Count the frequency of each binned frequency
freq_counter = Counter(binned_freqs)
# Find the top N most common binned frequencies
top_freqs = freq_counter.most_common(top_n)
# Extract just the frequencies from the top N tuples (freq, count)
top_freqs = [freq for freq, count in top_freqs]
return top_freqs

# Initialize a dictionary to store the top 5 frequencies for each channel
top_5_freqs_all_channels = {}
bin_width = 1.0

# Calculate the top 5 frequencies for each channel
for channel, freqs in dominant_freqs_summary.items():
top_5_freqs = get_top_n_frequencies(freqs, top_n=5, bin_width=bin_width)
top_5_freqs_all_channels[channel] = top_5_freqs
print(f"{channel}: Top 5 Frequencies = {top_5_freqs}")

..


2/05/2024

Download all YouTube videos in playlist (python)

pip install pytube

replace playlist url in string

.

from pytube import Playlist, YouTube

def download_video(url, max_attempts=3):
for attempt in range(1, max_attempts + 1):
try:
yt = YouTube(url)
video = yt.streams.get_highest_resolution()
video.download()
print(f"Downloaded: {yt.title}")
break
except Exception as e:
print(f"Error downloading video (attempt {attempt}): {url}\n{e}")
if attempt == max_attempts:
print(f"Failed to download video after {max_attempts} attempts: {url}")

# Replace with your playlist URL
playlist_url = 'https://www.youtube.com/playlist?list=xxx'

playlist = Playlist(playlist_url)

# Fetch video URLs
video_urls = playlist.video_urls

# Download each video
for url in video_urls:
download_video(url)

..


Thank you.

🙇🏻‍♂️

2/01/2024

get list of torch from conda installation

 input > conda list | grep torch

> conda list | grep torch
ffmpeg 4.3 hf484d3e_0 pytorch
libjpeg-turbo 2.0.0 h9bf148f_0 pytorch
pytorch 2.2.0 py3.8_cpu_0 pytorch
pytorch-mutex 1.0 cpu pytorch
torchaudio 2.2.0 py38_cpu pytorch
torchvision 0.17.0 py38_cpu pytorch

1/15/2024

unreal engine, create asset by python widget and copy asset to game env

 refer to code:

.

import unreal
import os

def main_process(input_args):
# Use a directory within your user's documents or another location you have write access to
local_directory = "/Users/user/Documents/Unreal Projects/prj_name/Content/prj_name/Scripts"
# Example usage
filename = "chamfered_cube.obj"
file_path = create_chamfered_cube_obj_file(filename, local_directory, 100.0, 0.1)
imported_asset_path = import_obj_to_unreal(file_path, "/Game/prj_name")
place_static_mesh_in_world('/Game/prj_name/chamfered_cube', (1000, 1000, 100))

def place_static_mesh_in_world(mesh_asset_path, location, rotation=(0, 0, 0), scale=(1, 1, 1)):
# Load the Static Mesh asset
static_mesh = unreal.load_asset(mesh_asset_path, unreal.StaticMesh)
# Get the current editor world
editor_world = unreal.EditorLevelLibrary.get_editor_world()
# Spawn a new StaticMeshActor in the world
static_mesh_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.StaticMeshActor, location, rotation
)
if static_mesh_actor:
# Access the StaticMeshComponent property and set the static mesh
static_mesh_component = static_mesh_actor.get_component_by_class(unreal.StaticMeshComponent)
if static_mesh_component:
static_mesh_component.set_static_mesh(static_mesh)
# Set the scale if necessary
static_mesh_actor.set_actor_scale3d(unreal.Vector(*scale))
print(f"Placed Static Mesh at location: {location}")
return static_mesh_actor
else:
print("Failed to access StaticMeshComponent.")
return None
else:
print("Failed to place Static Mesh in the world.")
return None

def import_obj_to_unreal(obj_file_path, unreal_asset_path):
# Set up the import task
import_task = unreal.AssetImportTask()
import_task.filename = obj_file_path # The full path to the OBJ file on disk
import_task.destination_path = unreal_asset_path # The path in Unreal where to import the asset
import_task.automated = True
import_task.save = True

# Set up the import options for Static Mesh
options = unreal.FbxImportUI()
# Set various options on the options object here...

import_task.options = options

# Execute the import task
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([import_task])

# Return the imported asset path if successful, None otherwise
return import_task.imported_object_paths[0] if import_task.imported_object_paths else None

import os

def create_chamfered_cube_obj_file(filename, directory, scale=1.0, chamfer_ratio=0.1):
# Calculate the chamfer size
chamfer_size = scale * chamfer_ratio
half_scale = scale / 2
inner_size = half_scale - chamfer_size

# Define the vertices for a chamfered cube
vertices = [
# Bottom vertices (4 corners)
f"v {-inner_size} {-inner_size} {-half_scale}", f"v {inner_size} {-inner_size} {-half_scale}",
f"v {inner_size} {inner_size} {-half_scale}", f"v {-inner_size} {inner_size} {-half_scale}",
# Top vertices (4 corners)
f"v {-inner_size} {-inner_size} {half_scale}", f"v {inner_size} {-inner_size} {half_scale}",
f"v {inner_size} {inner_size} {half_scale}", f"v {-inner_size} {inner_size} {half_scale}",
# Chamfer vertices on the bottom (4)
f"v {-half_scale} {-half_scale} {-inner_size}", f"v {half_scale} {-half_scale} {-inner_size}",
f"v {half_scale} {half_scale} {-inner_size}", f"v {-half_scale} {half_scale} {-inner_size}",
# Chamfer vertices on the top (4)
f"v {-half_scale} {-half_scale} {inner_size}", f"v {half_scale} {-half_scale} {inner_size}",
f"v {half_scale} {half_scale} {inner_size}", f"v {-half_scale} {half_scale} {inner_size}",
]

# Define the faces for a chamfered cube (using the vertex indices)
faces = [
# Bottom square
"f 1 2 3 4",
# Top square
"f 5 6 7 8",
# Side squares (4 sides)
"f 1 2 6 5", "f 2 3 7 6",
"f 3 4 8 7", "f 4 1 5 8",
# Chamfer triangles (8 triangles)
"f 1 9 2", "f 2 10 3",
"f 3 11 4", "f 4 12 1",
"f 5 13 6", "f 6 14 7",
"f 7 15 8", "f 8 16 5",
# Chamfer squares (connecting the triangles - 4 squares)
"f 9 10 14 13", "f 10 11 15 14",
"f 11 12 16 15", "f 12 9 13 16",
]
# Ensure the directory exists
if not os.path.exists(directory):
os.makedirs(directory)
# Create a full system file path
file_path = os.path.join(directory, filename)
# Writing vertices and faces to the OBJ file
with open(file_path, 'w') as file:
for v in vertices:
file.write(f"{v}\n")
for f in faces:
file.write(f"{f}\n")
print(f"Chamfered Cube OBJ file created at {file_path}")
return file_path

def create_cube_obj_file(filename, directory):
# Create a full system file path
file_path = os.path.join(directory, filename)
# Cube vertices and faces
vertices = [
"v -0.5 -0.5 -0.5", "v -0.5 -0.5 0.5", "v -0.5 0.5 -0.5", "v -0.5 0.5 0.5",
"v 0.5 -0.5 -0.5", "v 0.5 -0.5 0.5", "v 0.5 0.5 -0.5", "v 0.5 0.5 0.5"
]
faces = [
"f 1 3 4 2", "f 5 7 8 6", "f 1 5 6 2", "f 3 7 8 4",
"f 1 5 7 3", "f 2 6 8 4"
]
# Ensure the directory exists
if not os.path.exists(directory):
os.makedirs(directory)
# Writing vertices and faces to the OBJ file
with open(file_path, 'w') as file:
for v in vertices:
file.write(f"{v}\n")
for f in faces:
file.write(f"{f}\n")
print(f"Cube OBJ file created at {file_path}")
return file_path


..