Created
January 29, 2022 09:40
-
-
Save rajeshpachaikani/ac938ff3792b85b3bb8ba0da54b7269f to your computer and use it in GitHub Desktop.
This snippet demonstrates the use of hsv color space in editing the overall color output of the image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
#Reading an image (https://i.imgur.com/cdmHQiR.jpg) | |
img = cv2.imread('blue.jpg') | |
cv2.imshow('Original', img) | |
#Converting image to HSV Colorspace | |
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) | |
cv2.imshow('HSV', hsv) | |
#Splitting each component into different numpy array | |
h = hsv[:,:,0] | |
s = hsv[:,:,1] | |
v = hsv[:,:,2] | |
#Empty numpy array | |
hsv_new = np.zeros(hsv.shape, dtype=hsv.dtype) | |
#Dummy function for trackbar callback | |
def nothing(x): | |
pass | |
#Creating Trackbars | |
cv2.namedWindow('HSV_Sliders') | |
cv2.createTrackbar('Hue', 'HSV_Sliders', 0, 255, nothing) | |
cv2.createTrackbar('Sat', 'HSV_Sliders', 0, 255, nothing) | |
cv2.createTrackbar('Value', 'HSV_Sliders', 0, 255, nothing) | |
while 1: | |
#Getting Trackbar position | |
hue = cv2.getTrackbarPos('Hue', 'HSV_Sliders') | |
sat = cv2.getTrackbarPos('Sat', 'HSV_Sliders') | |
val = cv2.getTrackbarPos('Value', 'HSV_Sliders') | |
#Changing the image color by using the trackbar position value | |
hsv_new[:,:,0] = h/255*hue | |
hsv_new[:,:,1] = s/255*sat | |
hsv_new[:,:,2] = v/255*val | |
#Converting back to BGR image | |
hsv_new = cv2.cvtColor(hsv_new, cv2.COLOR_HSV2BGR) | |
cv2.imshow('HSV_new', hsv_new) | |
#Listening for key press events | |
key = cv2.waitKey(1) & 0xFF | |
#Quit if Esc key is pressed | |
if key == 27: | |
break | |
#Write new image to file if 's' key is pressed | |
if key == ord('s'): | |
fi_name = 'h_{}_s_{}_v_{}.jpg'.format(hue, sat, val) | |
cv2.imwrite(fi_name, hsv_new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment