Sagar Bharadwaj commited on
Commit
ff2a834
·
1 Parent(s): 89f7e8f

Added denoising to remove small color islands

Browse files
Files changed (1) hide show
  1. colorbynumber/simplify_image.py +42 -2
colorbynumber/simplify_image.py CHANGED
@@ -1,7 +1,8 @@
 
1
  import numpy as np
2
 
3
 
4
- def simplify_image(image, color_list):
5
  """
6
  Converts all colors in an image to the closest color in the color list.
7
 
@@ -24,4 +25,43 @@ def simplify_image(image, color_list):
24
  indices_color_choices = norm_diff.argmin(axis = -1)
25
  simplified_image = color_list[indices_color_choices.flatten(), :].reshape(image.shape)
26
 
27
- return simplified_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2 as cv
2
  import numpy as np
3
 
4
 
5
+ def _choose_closest_colors(image, color_list):
6
  """
7
  Converts all colors in an image to the closest color in the color list.
8
 
 
25
  indices_color_choices = norm_diff.argmin(axis = -1)
26
  simplified_image = color_list[indices_color_choices.flatten(), :].reshape(image.shape)
27
 
28
+ return simplified_image, indices_color_choices
29
+
30
+ def _denoise_image(image, h):
31
+ denoised_image = cv.fastNlMeansDenoisingColored(
32
+ src = image.astype(np.uint8),
33
+ dst = None,
34
+ h = h,
35
+ hColor = h,
36
+ templateWindowSize = 7,
37
+ searchWindowSize = 21
38
+ )
39
+ return denoised_image
40
+
41
+ def simplify_image(image,
42
+ color_list,
43
+ denoise = True,
44
+ denoise_h = 100
45
+ ):
46
+ """
47
+ Converts all colors in an image to the closest color in the color list.
48
+ Denoises if required.
49
+
50
+ Args:
51
+ image: Image in the RGB color space as a 3D array.
52
+ color_list: A list of tuples representing RGB values of allowed colors.
53
+
54
+ Returns:
55
+ A copy of the image with all colors replaced with the closest color in the list.
56
+ """
57
+
58
+ simplified_image, indices_color_choices = _choose_closest_colors(image, color_list)
59
+ if denoise:
60
+ # Denoising after simplifying image as denoising original image need not reduce the
61
+ # number of colors islands and also removed some key features from the original image.
62
+ simplified_image = _denoise_image(simplified_image, denoise_h)
63
+
64
+ # Simplying image again as denoising may have introduced new colors.
65
+ simplified_image, indices_color_choices = _choose_closest_colors(simplified_image, color_list)
66
+
67
+ return simplified_image, indices_color_choices