import cv2 as cv
import numpy as np
import copy as cp
filename = 'Genshin.jpg'
img = cv.imread(filename)
img = cv.resize(img, (1024,768), interpolation=cv.INTER_CUBIC)
all_clear = img.copy()
rows, cols = img.shape[:2]
ix, iy = -1, -1
hsv_or_rgb = False
drawing = False
is_mouse = False
rgb = ['R:', 'G:', 'B:']
hsv = ['H:', 'S:', 'V:']
contours = []
Text_clear = cp.deepcopy(img[:100, :cols//2])
def detect_and_measure(event, x, y, flags, param):
global ix, iy, Text_clear, hsv_or_rgb, rgb, hsv, is_mouse, contours
color = (255, 255, 255) if hsv_or_rgb else (0, 0, 255)
if event == cv.EVENT_LBUTTONDOWN:
is_mouse = True
ix, iy = x, y
if len(contours) == 1:
contours[0] = (ix, iy)
else:
contours.append((ix, iy))
pixel_value = img[y, x]
display = ''
if not hsv_or_rgb:
for i in range(3):
display += rgb[i] + str(pixel_value[2-i])+' '
else:
for i in range(3):
display += hsv[i] + str(pixel_value[i])+' '
print(pixel_value)
img[:100, :cols//2] = Text_clear
cv.putText(img, display, (0, 50), cv.FONT_HERSHEY_COMPLEX, 1, color, 1, cv.LINE_AA)
elif event == cv.EVENT_MOUSEMOVE:
if is_mouse:
cv.circle(img, (x, y), 3, color, -1)
contours.append((x, y))
elif event == cv.EVENT_LBUTTONUP:
is_mouse = False
contour = np.array([contours])
area = cv.contourArea(contour)
length = cv.arcLength(contour, False)
display = 'Area:' + str(int(area*100)/100.0) + ' Length:' + str(int(length*100)/100.0)
cv.putText(img, display, (0, 80), cv.FONT_HERSHEY_COMPLEX, 1, color, 1, cv.LINE_AA)
contours.clear()
cv.namedWindow('image')
cv.setMouseCallback('image', detect_and_measure)
while 1:
cv.imshow('image', img)
key = cv.waitKey(1)
key = key & 0xFF
if key == 27:
break
elif key == ord('q'):
img = all_clear.copy()
if not hsv_or_rgb:
img = cv.cvtColor(img, cv.COLOR_BGR2HSV)
Text_clear = cp.deepcopy(img[:100, :cols // 2])
hsv_or_rgb = True
else:
img = cv.cvtColor(img, cv.COLOR_HSV2BGR)
Text_clear = cp.deepcopy(img[:100, :cols // 2])
hsv_or_rgb = False
all_clear = img.copy()
elif key == ord('e'):
img = all_clear.copy()
cv.destroyAllWindows()