|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +import pandas as pd |
| 4 | +import argparse |
| 5 | + |
| 6 | +# Using argparse library can directly give an image path from the command prompt |
| 7 | +ap = argparse.ArgumentParser() |
| 8 | +ap.add_argument('-i', '--image', required=True, help="Image Path") |
| 9 | +args = vars(ap.parse_args()) |
| 10 | +img_path = args['image'] |
| 11 | + |
| 12 | +# Reading image with opencv |
| 13 | +img = cv2.imread(img_path) |
| 14 | + |
| 15 | +# Global Variables |
| 16 | +clicked = False |
| 17 | +r = g = b = xpos = ypos = 0 |
| 18 | + |
| 19 | + |
| 20 | +# Reading csv file using pandas |
| 21 | +index = ["color", "color_name", "hex", "R", "G", "B"] |
| 22 | +csv = pd.read_csv('colors.csv', names=index, header=None) |
| 23 | + |
| 24 | + |
| 25 | +def draw_function(event, x, y, flags, param): |
| 26 | + if event == cv2.EVENT_LBUTTONDBLCLK: |
| 27 | + global b, g, r, xpos, ypos, clicked |
| 28 | + clicked = True |
| 29 | + xpos = x |
| 30 | + ypos = y |
| 31 | + b, g, r = img[y, x] |
| 32 | + b = int(b) |
| 33 | + g = int(g) |
| 34 | + r = int(r) |
| 35 | + |
| 36 | + |
| 37 | +def getColorName(R, G, B): |
| 38 | + minimum = 10000 |
| 39 | + for i in range(len(csv)): |
| 40 | + d = abs(R - int(csv.loc[i, "R"])) + abs(G - int(csv.loc[i, "G"])) + abs(B - int(csv.loc[i, "B"])) |
| 41 | + if(d<=minimum): |
| 42 | + minimum = d |
| 43 | + cname = csv.loc[i, "color_name"] |
| 44 | + return cname |
| 45 | + |
| 46 | + |
| 47 | +cv2.namedWindow('image') |
| 48 | +cv2.setMouseCallback('image',draw_function) |
| 49 | + |
| 50 | + |
| 51 | +while(1): |
| 52 | + |
| 53 | + cv2.imshow("image",img) |
| 54 | + if (clicked): |
| 55 | + |
| 56 | + # cv2.rectangle(image, startpoint, endpoint, color, thickness)-1 fills entire rectangle |
| 57 | + cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1) |
| 58 | + |
| 59 | + # Creating text string to display( Color name and RGB values ) |
| 60 | + text = getColorName(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b) |
| 61 | + |
| 62 | + # cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType ) |
| 63 | + cv2.putText(img, text,(50,50),2,0.8,(255,255,255),2,cv2.LINE_AA) |
| 64 | + |
| 65 | + # For very light colours display text in black colour |
| 66 | + if(r+g+b>=600): |
| 67 | + cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA) |
| 68 | + |
| 69 | + clicked=False |
| 70 | + |
| 71 | + # Break the loop when user hits 'esc' key |
| 72 | + if cv2.waitKey(20) & 0xFF ==27: |
| 73 | + break |
| 74 | + |
| 75 | +cv2.destroyAllWindows() |
0 commit comments