|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +import pandas as pd |
| 4 | +import argparse |
| 5 | +import sys |
| 6 | + |
| 7 | +# Creating argument parser to take image path from command line |
| 8 | +ap = argparse.ArgumentParser() |
| 9 | +ap.add_argument('-i', '--image', required=True, help="Image Path") |
| 10 | +args = vars(ap.parse_args()) |
| 11 | +img_path = args['image'] |
| 12 | + |
| 13 | +# Reading the image with opencv |
| 14 | +img = cv2.imread(img_path) |
| 15 | +print("Press Esc to exit the program! :)") |
| 16 | + |
| 17 | +# declaring global variables (are used later on) |
| 18 | +clicked = False |
| 19 | +r = g = b = xpos = ypos = 0 |
| 20 | + |
| 21 | +# Reading csv file with pandas and giving names to each column |
| 22 | +index = ["color", "color_name", "hex", "R", "G", "B"] |
| 23 | +csv = pd.read_csv('colors.csv', names=index, header=None) |
| 24 | + |
| 25 | + |
| 26 | +# function to calculate minimum distance from all colors and get the most matching color |
| 27 | +def getColorName(R, G, B): |
| 28 | + minimum = sys.maxsize |
| 29 | + for i in range(len(csv)): |
| 30 | + d = abs(R - int(csv.loc[i, "R"])) + abs(G - int(csv.loc[i, "G"])) + abs(B - int(csv.loc[i, "B"])) |
| 31 | + if d <= minimum: |
| 32 | + minimum = d |
| 33 | + cname = csv.loc[i, "color_name"] |
| 34 | + return cname |
| 35 | + |
| 36 | +# function to get x,y coordinates of mouse double click |
| 37 | +def draw_function(event, x, y, flags, param): |
| 38 | + if event == cv2.EVENT_LBUTTONDOWN: |
| 39 | + global b, g, r, xpos, ypos, clicked |
| 40 | + clicked = True |
| 41 | + print("clicked!") |
| 42 | + xpos = x |
| 43 | + ypos = y |
| 44 | + b, g, r = img[y, x] |
| 45 | + b = int(b) |
| 46 | + g = int(g) |
| 47 | + r = int(r) |
| 48 | + |
| 49 | + |
| 50 | +cv2.namedWindow('Photo') |
| 51 | +cv2.setMouseCallback('Photo', draw_function) |
| 52 | + |
| 53 | +while 1: |
| 54 | + |
| 55 | + cv2.imshow("Photo", img) |
| 56 | + if clicked: |
| 57 | + # image, startpoint, endpoint, color, thickness)-1 fills entire rectangle |
| 58 | + cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1) |
| 59 | + |
| 60 | + # Creating text string to display( Color name and RGB values ) |
| 61 | + colorName = getColorName(r, g, b) + " R=" + str(r) + " G=" + str(g) + " B=" + str(b) |
| 62 | + |
| 63 | + # cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType ) |
| 64 | + cv2.putText(img, colorName, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA) |
| 65 | + |
| 66 | + clicked = False |
| 67 | + |
| 68 | + # Exit Program |
| 69 | + if cv2.waitKey(20) & 0xFF == 27: |
| 70 | + break |
| 71 | + |
| 72 | +cv2.destroyAllWindows() |
0 commit comments