I want to customize the image color to make a similar image with color variants.
Example :
For the above image, I want to replace the red color with other colors like blue, green, yellow, black, etc.
I tried :
from PIL import Image
filename ="./Logo.jpg"
picture = Image.open(filename, 'r')
_colors = [(255, 255, 255), (128, 128, 0), (128, 128, 128), (192, 128, 0), (128, 64, 0), (0, 192, 0), (128, 64, 128), (255, 255, 255)]
width, height = picture.size
for x in range(0, width):
for y in range(0, height):
current_color = picture.getpixel((x,y))
# print (current_color)
if current_color in _colors:
picture.putpixel((x,y), (255,5, 255))
# print ("Y")
picture.save("./test/change.png")
The above code is quite common code which is suggested for most of them. But it is quite hard to as it replaces the pixel in the list " _colors " The output image is :
Any solution to the above problem? Any smart way to deal with this using machine learning? Any solution using another programming language?
I'm not familiar with PIL, and I heard that it's slow. So here's a OpenCV version:
# for red color, it's easier to work with negative image
# since hue is in [170, 180] or [0,10]
hsv_inv = cv2.cvtColor(255-img, cv2.COLOR_BGR2HSV)
# these are cyan limit, but we're working on negative image, so...
lower_range = np.array([80,0,0])
upper_range = np.array([100,255,255])
# mask the red
mask = cv2.inRange(hsv_inv, lower_range, upper_range)
# replace red by green
green_hsv = hsv_inv.copy()
green_hsv[np.where(mask)] += np.array([60,0,0], dtype=np.uint8)
green_img = 255 - cv2.cvtColor(green_hsv, cv2.COLOR_HSV2BGR)
purple_hsv = hsv_inv.copy()
purple_hsv[np.where(mask)] -= np.array([30,0,0], dtype=np.uint8)
purple_img = 255 - cv2.cvtColor(purple_hsv, cv2.COLOR_HSV2BGR)
And result, pls ignore the ticks as I showed them by matplotlib.