-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
55 lines (36 loc) · 1.3 KB
/
utils.py
File metadata and controls
55 lines (36 loc) · 1.3 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
import hashlib
from pathlib import Path
import cv2
import numpy as np
def list_to_color(l: list) -> np.uint8:
return np.uint8([[l]])
def read_file(path: Path) -> cv2.typing.MatLike:
""" Reads an image file from path containing any symbols
cv2.imread crashes if path contains cyrrilic letters
"""
with open(path, "rb") as file:
chunk = file.read()
chunk = np.frombuffer(chunk, dtype=np.uint8)
return cv2.imdecode(chunk, cv2.IMREAD_COLOR)
def write_file(path: Path, image: cv2.typing.MatLike):
# if not path.is_file():
# raise ValueError("path has to be a file.")
_, image_buffer = cv2.imencode('.jpg', image)
image_buffer.tofile(path)
def reverse_mask(mask: np.ndarray):
if mask.ndim != 2:
raise ValueError("mask dimension count must be 2.")
mask = 255 - mask
return mask
def imshow_mask(mask: np.ndarray):
if mask.ndim != 2:
raise ValueError("mask dimension count must be 2.")
preview = np.zeros((*mask.shape, 3))
preview[mask == 255] = [255] * 3
cv2.imshow("Mask Preview", mask)
def get_file_md5(path: Path) -> str:
md5 = hashlib.md5()
with open(path, mode="rb") as file:
while chunk := file.read(md5.block_size):
md5.update(chunk)
return md5.hexdigest()