Uzaiir commited on
Commit
bc1b330
·
verified ·
1 Parent(s): 4124dde

Update src/utils.py

Browse files
Files changed (1) hide show
  1. src/utils.py +92 -90
src/utils.py CHANGED
@@ -1,90 +1,92 @@
1
- import numpy as np
2
- import cv2
3
- from PIL import Image
4
-
5
- def convert_to_bw(image):
6
- """
7
- Converts a PIL image to black & white (grayscale),
8
- and then back to RGB to maintain compatibility with other processes.
9
-
10
- Parameters:
11
- image (PIL.Image): Input RGB image.
12
-
13
- Returns:
14
- PIL.Image: Black & white image in RGB format.
15
- """
16
- return image.convert("L").convert("RGB")
17
-
18
- def load_colorization_model():
19
- """
20
- Loads the pre-trained Caffe model for colorizing black & white images.
21
-
22
- Model files required:
23
- - colorization_deploy_v2.prototxt
24
- - colorization_release_v2.caffemodel
25
- - pts_in_hull.npy
26
-
27
- Returns:
28
- cv2.dnn_Net: Loaded and initialized OpenCV DNN colorization model.
29
- """
30
- # Paths to model architecture, weights, and cluster centers
31
- proto_file = "models/colorization_deploy_v2.prototxt"
32
- model_file = "models/colorization_release_v2.caffemodel"
33
- cluster_file = "models/pts_in_hull.npy"
34
-
35
-
36
- # Load the model using OpenCV DNN module
37
- net = cv2.dnn.readNetFromCaffe(proto_file, model_file)
38
- pts = np.load(cluster_file)
39
-
40
- # Populate cluster centers as 1x1 convolution kernel
41
- class8_ab = net.getLayerId("class8_ab")
42
- conv8_313_rh = net.getLayerId("conv8_313_rh")
43
-
44
- pts = pts.transpose().reshape(2, 313, 1, 1)
45
- net.getLayer(class8_ab).blobs = [pts.astype(np.float32)]
46
- net.getLayer(conv8_313_rh).blobs = [np.full([1, 313], 2.606, dtype=np.float32)]
47
-
48
- return net
49
-
50
- def colorize_bw_image(pil_img, net):
51
- """
52
- Colorizes a grayscale (black & white) image using a pre-trained DNN model.
53
-
54
- Parameters:
55
- pil_img (PIL.Image): Input grayscale image in RGB format.
56
- net (cv2.dnn_Net): Loaded OpenCV DNN colorization model.
57
-
58
- Returns:
59
- PIL.Image: Colorized image in RGB format.
60
- """
61
- # Convert PIL image to NumPy array
62
- img = np.array(pil_img)
63
- img_rgb = img[:, :, [2, 1, 0]] # Convert RGB to BGR
64
- img_rgb = img_rgb.astype("float32") / 255.0
65
- # Convert to LAB color space and extract L channel
66
- img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2LAB)
67
- l_channel = img_lab[:, :, 0]
68
-
69
- # Resize L channel to match model input size and normalize
70
- input_l = cv2.resize(l_channel, (224, 224))
71
- input_l -= 50
72
-
73
- # Run inference
74
- net.setInput(cv2.dnn.blobFromImage(input_l))
75
- ab_channels = net.forward()[0, :, :, :].transpose((1, 2, 0)) # shape: (56, 56, 2)
76
-
77
- # Resize predicted ab channels to match original image size
78
- ab_channels = cv2.resize(ab_channels, (img.shape[1], img.shape[0]))
79
-
80
- # Merge original L channel with predicted ab channels
81
- lab_output = np.concatenate((l_channel[:, :, np.newaxis], ab_channels), axis=2)
82
-
83
- # Convert LAB to BGR, clip values, and convert to uint8
84
- bgr_out = cv2.cvtColor(lab_output, cv2.COLOR_LAB2BGR)
85
- bgr_out = np.clip(bgr_out, 0, 1)
86
-
87
-
88
- # Convert back to RGB and return as PIL Image
89
- final_rgb = (bgr_out[:, :, [2, 1, 0]] * 255).astype("uint8")
90
- return Image.fromarray(final_rgb)
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ from PIL import Image
4
+ import os
5
+
6
+ def convert_to_bw(image):
7
+ """
8
+ Converts a PIL image to black & white (grayscale),
9
+ and then back to RGB to maintain compatibility with other processes.
10
+
11
+ Parameters:
12
+ image (PIL.Image): Input RGB image.
13
+
14
+ Returns:
15
+ PIL.Image: Black & white image in RGB format.
16
+ """
17
+ return image.convert("L").convert("RGB")
18
+
19
+ def load_colorization_model():
20
+ """
21
+ Loads the pre-trained Caffe model for colorizing black & white images.
22
+
23
+ Model files required:
24
+ - colorization_deploy_v2.prototxt
25
+ - colorization_release_v2.caffemodel
26
+ - pts_in_hull.npy
27
+
28
+ Returns:
29
+ cv2.dnn_Net: Loaded and initialized OpenCV DNN colorization model.
30
+ """
31
+ # Paths to model architecture, weights, and cluster centers
32
+ base_path = os.path.join(os.path.dirname(__file__), "models")
33
+ proto_file = "models/colorization_deploy_v2.prototxt"
34
+ model_file = "models/colorization_release_v2.caffemodel"
35
+ cluster_file = "models/pts_in_hull.npy"
36
+
37
+
38
+ # Load the model using OpenCV DNN module
39
+ net = cv2.dnn.readNetFromCaffe(proto_file, model_file)
40
+ pts = np.load(cluster_file)
41
+
42
+ # Populate cluster centers as 1x1 convolution kernel
43
+ class8_ab = net.getLayerId("class8_ab")
44
+ conv8_313_rh = net.getLayerId("conv8_313_rh")
45
+
46
+ pts = pts.transpose().reshape(2, 313, 1, 1)
47
+ net.getLayer(class8_ab).blobs = [pts.astype(np.float32)]
48
+ net.getLayer(conv8_313_rh).blobs = [np.full([1, 313], 2.606, dtype=np.float32)]
49
+
50
+ return net
51
+
52
+ def colorize_bw_image(pil_img, net):
53
+ """
54
+ Colorizes a grayscale (black & white) image using a pre-trained DNN model.
55
+
56
+ Parameters:
57
+ pil_img (PIL.Image): Input grayscale image in RGB format.
58
+ net (cv2.dnn_Net): Loaded OpenCV DNN colorization model.
59
+
60
+ Returns:
61
+ PIL.Image: Colorized image in RGB format.
62
+ """
63
+ # Convert PIL image to NumPy array
64
+ img = np.array(pil_img)
65
+ img_rgb = img[:, :, [2, 1, 0]] # Convert RGB to BGR
66
+ img_rgb = img_rgb.astype("float32") / 255.0
67
+ # Convert to LAB color space and extract L channel
68
+ img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2LAB)
69
+ l_channel = img_lab[:, :, 0]
70
+
71
+ # Resize L channel to match model input size and normalize
72
+ input_l = cv2.resize(l_channel, (224, 224))
73
+ input_l -= 50
74
+
75
+ # Run inference
76
+ net.setInput(cv2.dnn.blobFromImage(input_l))
77
+ ab_channels = net.forward()[0, :, :, :].transpose((1, 2, 0)) # shape: (56, 56, 2)
78
+
79
+ # Resize predicted ab channels to match original image size
80
+ ab_channels = cv2.resize(ab_channels, (img.shape[1], img.shape[0]))
81
+
82
+ # Merge original L channel with predicted ab channels
83
+ lab_output = np.concatenate((l_channel[:, :, np.newaxis], ab_channels), axis=2)
84
+
85
+ # Convert LAB to BGR, clip values, and convert to uint8
86
+ bgr_out = cv2.cvtColor(lab_output, cv2.COLOR_LAB2BGR)
87
+ bgr_out = np.clip(bgr_out, 0, 1)
88
+
89
+
90
+ # Convert back to RGB and return as PIL Image
91
+ final_rgb = (bgr_out[:, :, [2, 1, 0]] * 255).astype("uint8")
92
+ return Image.fromarray(final_rgb)