File size: 8,142 Bytes
b3e34bd fe301ed b3e34bd fe301ed b3e34bd fe301ed b3e34bd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
from PIL import Image
import os
import re
import sys
import json
import uuid
import struct
from collections import defaultdict
def get_png_dimensions(file_path):
"""
Returns the (width, height) of a PNG image by reading the file's metadata.
"""
with open(file_path, 'rb') as f:
# PNG files start with an 8-byte signature
signature = f.read(8)
# Check if the file is a valid PNG by checking the signature
if signature != b'\x89PNG\r\n\x1a\n':
raise ValueError("Not a valid PNG file")
# The IHDR chunk starts after the 8-byte signature and 4-byte length field
f.read(4) # Skip the length of the IHDR chunk
# Ensure we're reading the IHDR chunk
ihdr_chunk = f.read(4)
if ihdr_chunk != b'IHDR':
raise ValueError("Invalid PNG IHDR chunk")
# Read width and height from the IHDR chunk (8 bytes total)
width, height = struct.unpack('>II', f.read(8))
return width, height
def get_jpeg_dimensions(file_path):
"""
Returns the (width, height) of a JPG image by reading the file's metadata.
"""
with open(file_path, 'rb') as f:
f.seek(0)
data = f.read(24)
# Check if file is JPEG
if data[0:2] == b'\xff\xd8': # JPEG files start with 0xFFD8
while True:
f.seek(2, 1) # Skip marker
marker = f.read(2)
if marker[0] == 0xFF and marker[1] == 0xC0: # Start of Frame marker
f.seek(3, 1) # Skip precision byte
height = int.from_bytes(f.read(2), 'big')
width = int.from_bytes(f.read(2), 'big')
return width, height
else:
size = int.from_bytes(f.read(2), 'big')
f.seek(size - 2, 1) # Skip to the next block
else:
raise ValueError("Not a JPEG file")
def get_image_dimensions(file_path):
extension = os.path.splitext(file_path)[-1].lower()
if extension == '.jpg' or extension == '.jpeg':
return get_jpeg_dimensions(file_path)
elif extension == '.png':
return get_png_dimensions(file_path)
else:
raise ValueError("Unsupported file format")
# Get the directory of the current script
script_dir = os.path.dirname(os.path.abspath(__file__))
# Construct the full path to the target directory
base_dir = os.path.join(script_dir, '..', 'result', 'flux-dev')
output_dir = os.path.join(script_dir, '..', 'output/icat_projects')
if not os.path.exists(base_dir):
print(f"The path {base_dir} does not exist!")
sys.exit(1) # Exit the program with a non-zero status to indicate an error
else:
print(f"Searching for images in {base_dir}.")
os.makedirs(output_dir, exist_ok=True)
# Regular expression to match the five-digit number in the file names
pattern = re.compile(r'\d{5}')
# Dictionary to store file groups
file_groups = defaultdict(list)
# Walk through all subdirectories and files
for root, dirs, files in os.walk(base_dir):
for file in files:
# Search for the five-digit number in the file name
match = pattern.search(file)
if match:
# Get the five-digit number
number = match.group()
# Add the file (with its full path) to the corresponding group
file_groups[number].append(os.path.join(root, file))
# Fill JSON structure with grouped files
for number, group in file_groups.items():
media_files = []
media_order = []
# JSON structure template
json_structure = {
"uiVisibility": {
"antiAliasSelect": True,
"fullscreenButton": True,
"gridSelect": True,
"helpButton": True,
"layersButton": True,
"layoutTabs": True,
"loopButton": True,
"mediaInfo": True,
"pixelDataButton": False,
"progressBar": True,
"setSelect": False,
"speedSelect": True,
"startEndTime": True,
"timeDisplay": True,
"titleBar": True,
"videoControls": True,
"zoomSelect": True,
"contentSidebar": True,
"timeline": True,
"controlBar": True,
"addFilterBtn": True,
"addLogoBtn": True,
"inOutSlider": True,
"timelineInOutSlider": False,
"appSettingsBtn": True
},
"sets": []
}
for file_path in group:
file_name = os.path.basename(file_path)
base_name = file_name.rsplit('.', 1)[0]
hex_id = uuid.uuid4().hex # Generate a unique hex ID for each file
cleaned_path = os.path.abspath(file_path).replace('\\', '%5C').replace(':', '%3A')
width, height = get_image_dimensions(file_path)
# Example media entry
media_entry = {
"id": hex_id,
"created": int(os.path.getctime(file_path) * 1000),
"codec": "PNG",
"bitrate": 0,
"width": width,
"height": height,
"type": "image",
"fps": 0,
"duration": 0,
"size": os.path.getsize(file_path),
"modified": int(os.path.getmtime(file_path) * 1000),
"hasAudio": False,
"timestamps": [],
"path": os.path.abspath(file_path).replace("/", "\\"),
"name": file_name,
"base": base_name,
"originalBase": base_name,
"extension": file_name.split('.')[-1],
"format": "PNG",
"x": 0,
"y": 0,
"z": 100,
"startTime": 0,
"thumbnails": [],
"labelVisibility": {
"codec": False,
"bitrate": False,
"dimensions": False,
"format": False,
"fps": False,
"duration": False,
"startTime": False
},
"muted": True,
"visible": True,
"shaderId": "",
"shaderInputs": [],
"shaderSettings": {},
"shaderSource": "",
"showShader": True,
"src": f"icat://localhost/?src={cleaned_path}",
"mediaOverlay": "",
"frameImages": [],
"showFrameImages": True,
"infoTexts": [],
"showInfoText": False
}
media_files.append(media_entry)
media_order.append(hex_id)
# Add the set entry to JSON structure
set_id = str(uuid.uuid4().hex)
json_structure["activeSet"] = set_id
json_structure["sets"].append({
"id": set_id,
"created": 1724539610545,
"label": f"Einstellen {len(json_structure['sets']) + 1}",
"antiAlias": False,
"endTime": 1e+29,
"grid": 0,
"layout": "split",
"overlayOrder": [],
"looping": True,
"boomerang": False,
"mediaOrder": media_order,
"x": 2170.7728827197748,
"y": 0,
"z": 30.340576171875,
"speed": 1,
"splitposition": 0.5,
"startTime": 0,
"time": 0,
"viewport": {
"top": 93.17708587646484,
"left": 0,
"paneWidth": 2560,
"paneHeight": 932.0625,
"height": 932.0625,
"width": 2560,
"minZoom": 30.340576171875,
"fitScale": 0.30340576171875,
"fitWidth": 4096,
"fitHeight": 3072,
"fitPaneWidth": 4096,
"fitPaneHeight": 3072,
"contentWidth": 4096,
"contentHeight": 3072
},
"gamma": 1,
"exposure": 1,
"media": media_files,
"overlays": []
})
json_filename = os.path.join(output_dir, f"image_comparison_{number}.json")
with open(json_filename, 'w') as json_file:
json.dump(json_structure, json_file, indent=4)
print(f"JSON-Datei für Gruppe {number} wurde geschrieben: {json_filename}") |