I have a task to change the red rectangle to blue with the given hsv parameters: -0.3333, -0.05, -0.05
then save the new image.
I used the following site to demonstrate the blue square transform.
To transform it to blue I have to subtract the given parameters from the image hsv.
h: 1 - 0.3333 = 0.667 , s: 1 - 0.05 = 0.95, v: 1 - 0.05 = 0.95
I assume first I have to convert rbg image to hsv but I couldn't figure out how can I transform it to blue with the given parameters.
import cv2
image = cv2.imread('C:\projects\red.jpg')
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
cv2.imwrite('C:\projects\hsv_blue.jpg', hsv_image)
cv2.imshow('HSV image', hsv_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
I appreciate any help.
CodePudding user response:
That will work, 255 is 100% on OpenCV.
image = cv2.imread('img_4.png')
img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
img_hsv[:, :, 0] = (img_hsv[:, :, 0] - int(255 * 0.3333)) % 255
img_hsv[:, :, 1] = (img_hsv[:, :, 1] - int(255 * 0.05)) % 255
img_hsv[:, :, 2] = (img_hsv[:, :, 2] - int(255 * 0.05)) % 255
img_bgr = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB)
cv2.imwrite("modified_image.jpg", img_bgr)
CodePudding user response:
In general, you should identify the red square, make a mask to change the pixels colors and change it.
The code below might help, but I use opencv HSV color range ( H [0-180], S [0-255] , V [0-255] ). I could not understand your HSV parameters range.
import cv2
import numpy as np
#Load image
image = cv2.imread('redsquare.jpg')
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
#Define red square area
hsv_lower_red = np.array([150,50,70])
hsv_upper_red = np.array([180,255,255])
mask = cv2.inRange(image_hsv, hsv_lower_red, hsv_upper_red)
#Change red to blue
hsv_blue_color = np.uint8([[[120,255,255 ]]])
image_hsv[mask > 0] = hsv_blue_color
#Save results to file
image = cv2.cvtColor(image_hsv, cv2.COLOR_HSV2BGR)
cv2.imwrite('bluesquare.jpg', image)