-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_image.py
More file actions
92 lines (73 loc) · 2.72 KB
/
Copy pathparse_image.py
File metadata and controls
92 lines (73 loc) · 2.72 KB
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
from PIL import Image
import pandas as pd
from sklearn.neighbors import NearestNeighbors
import multiprocessing as mp
import numpy as np
import sys
import math
import logging
def downscale_image(img, method=Image.LANCZOS):
encoder_max = {"width": 8192, "height": 4320}
target_height = encoder_max["height"] / 31 # "how many banners can fit?"
target_width = encoder_max["width"] / 88
original_width, original_height = img.size
if original_width > original_height: # Which dimension is larger?
if original_width > target_width:
ratio = math.ceil(original_width / target_width)
target_width = original_width / ratio
target_height = original_height / ratio
else:
return img
elif original_height > target_height:
ratio = math.ceil(original_height / target_height)
target_width = original_width / ratio
target_height = original_height / ratio
else:
return img
resized_img = img.resize((round(target_width), round(target_height)), method)
resized_img.save("./downscaled.png")
return resized_img
# Define the function to find the closest image
def find_closest_image(args):
x, y, pixel_rgb, nn, image_data = args
distance, index = nn.kneighbors([pixel_rgb])
return x, y, image_data.iloc[index[0]]["Image Name"].values[0]
def load_and_parse(image_path):
# Load the image
img = Image.open(image_path)
img = downscale_image(img)
if img.mode != "RGB":
img = img.convert("RGB")
pixels = img.load()
# Load your CSV data
csv_path = "image_values.csv"
image_data = pd.read_csv(csv_path)
# Assuming your CSV has columns 'Image Name', 'Flashy', 'Mean Red', 'Mean Green', 'Mean Blue'
# Filter out flashy images if necessary
image_data = image_data[image_data["Flashy"] == False]
# Extract RGB values
rgb_values = image_data[["Mean Red", "Mean Green", "Mean Blue"]].values
# Build a k-d tree
nn = NearestNeighbors(n_neighbors=1, algorithm="kd_tree")
nn.fit(rgb_values)
# Prepare arguments for multiprocessing: list of (x, y, pixel_value)
args_list = [
(x, y, pixels[x, y], nn, image_data)
for x in range(img.width)
for y in range(img.height)
]
# Setup multiprocessing pool
pool = mp.Pool(mp.cpu_count())
# pprint(args_list)
# Process each pixel in parallel
results = pool.map(find_closest_image, args_list)
# Cleanup
pool.close()
pool.join()
# Convert results to a DataFrame
df = pd.DataFrame(results, columns=["x", "y", "func_result"])
# Save to CSV
df.to_csv("pixel_results.csv", index=False)
if __name__ == "__main__":
image_path = sys.argv[1]
load_and_parse(image_path)