-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
164 lines (126 loc) · 3.94 KB
/
utils.py
File metadata and controls
164 lines (126 loc) · 3.94 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
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
import copy
import cv2 as cv
import numpy as np
from PIL import Image
def biter(b: int, step=1):
"""
Iterate over the bits of an integer.
Args:
b (int): The integer to generate binary numbers for.
Yields:
int: The binary numbers.
"""
for i in range(0, 8, step):
yield b >> i & 1
def fourcc(name: str):
"""
Get the fourcc code for a codec name.
Args:
name (str): The name of the codec.
Returns:
str: The fourcc code.
"""
return getattr(cv, "VideoWriter_fourcc")(*name)
class Encoding:
"""
Encode/decode byte data to image.
"""
@staticmethod
def encode(data: bytes, image_size: tuple[int, int], output_path: str):
"""
Encode data to image.
Args:
data (bytes): The data to encode.
image_size (tuple[int, int]): The size of the image.
output_path (str): The path to save the image.
"""
raise NotImplementedError
@staticmethod
def decode(path: str):
"""
Decode image to data.
Args:
path (str): The path to the image.
"""
raise NotImplementedError
class BitEncoding(Encoding):
"""
Encode/decode byte data to image where 0 is black and 1 is white (binary).
"""
@staticmethod
def encode(data: bytes, image_size: tuple[int, int], output_path: str):
im = Image.new("1", image_size)
i, x, y = 0, 0, 0
for byte in data:
for bit in reversed(list(biter(byte))):
im.putpixel((x, y), bit)
x += 1
# next row
if x >= image_size[0]:
x = 0
y += 1
# next image
if y >= image_size[1]:
im.save(output_path.replace("%num%", str(i)))
im = Image.new("1", image_size)
x, y = 0, 0
i += 1
im.save(output_path.replace("%num%", str(i)))
@staticmethod
def decode(path: str) -> bytes:
im = Image.open(path)
out = bytearray()
data = list(im.getdata())
for i in range(0, len(data), 8):
bits = data[i : i + 8]
bits = [1 if b == 255 else 0 for b in bits]
byte = int("".join(map(str, bits)), 2)
out.append(byte)
return bytes(out)
@staticmethod
def remove_endl(data: bytes) -> bytes:
"""
Remove last empty block of data.
Args:
data (bytes): The data to process.
Returns:
bytes: The data without the last empty block.
"""
i = 0
for i in range(len(data) - 1, 0, -1):
if data[i] != 0:
break
return bytes(data[: i + 1])
class VideoEncoding:
"""
Encode/decode images to video.
"""
@staticmethod
def encode(images: list[str], video_size: tuple[int, int], output_path: str):
video_codec = fourcc("RGBA")
video = cv.VideoWriter(output_path, video_codec, 1, video_size)
for imagepath in images:
frame = cv.imread(imagepath)
video.write(frame)
video.release()
@staticmethod
def decode(path: str, image_output: str):
cap = cv.VideoCapture(path)
if not cap.isOpened():
raise Exception("Can't open video")
i = 0
last_frame = None
while True:
ret, frame = cap.read()
if not ret:
break
# convert color space to RGB
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# don't save duplicate frames
if type(last_frame) is np.ndarray and np.array_equal(frame, last_frame):
continue
# save frame
last_frame = copy.deepcopy(frame)
Image.fromarray(frame).save(image_output.replace("%num%", str(i)), "PNG")
i += 1
cap.release()