0

how to achieve img_update(hue_offset) function by changing the values of the hue channel by a dynamic hue_offset. To implement img_update(hue_offset) function, to achieve this Submission: 1.Change the values of the hue channel by a dynamic hue_offset.

enter image description here

import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

def showImage(img, show_window_now = True):
    # TODO: Convert the channel order of an image from BGR to RGB
    #
    # img = str(img)
    img2 = cv2.imread(img)
    img = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)

    plt_img = plt.imshow(img)
    if show_window_now:
       plt.show()
    return plt_img
# Prepare to show the original image and keep a reference so that we can update the image plot later.

plt.figure(figsize=(4, 6))
img = "hummingbird_from_pixabay.png"
plt_img = showImage(img, False)

# TODO: Convert the original image to HSV color space.
#

img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)

def img_update(hue_offset):
    print("Set hue offset to " + str(hue_offset))
    # TODO: Change the hue channel of the HSV image by `hue_offset`.
    # Mind that hue values in OpenCV range from 0-179.
    # ???

    # TODO: Convert the modified HSV image back to RGB
    # and update the image in the plot window using `plt_img.set_data(img_rgb)`.
    #
    # ???
    #

# Create an interactive slider for the hue value offset.

ax_hue = plt.axes([0.1, 0.04, 0.8, 0.06]) # x, y, width, height
slider_hue = Slider(ax=ax_hue, label='Hue', valmin=0, valmax=180, valinit=0, valstep=1)
slider_hue.on_changed(img_update)

# Now actually show the plot window
plt.show()
guigui
  • 1
  • 1
  • 4
  • 2
    What do you think your code is doing? How do you interpret "Change the values of the hue channel by a dynamic hue_offset"? What is your code actually doing? How is this "problematic"? – beaker May 08 '21 at 16:01
  • In fact, it is necessary to implement img_update(hue_offset) function to dynamically display photos under different hue values. – guigui May 08 '21 at 22:07

1 Answers1

4

This is one way to do that in Python/OpenCV.

Input:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread("bird.png")

# convert img to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]

# shift the hue
# cv2 will clip automatically to avoid color wrap-around
huechange = 85   # 0 is no change; 0<=huechange<=180
hnew = cv2.add(h, huechange)

# combine new hue with s and v
hsvnew = cv2.merge([hnew,s,v])

# convert from HSV to BGR
result = cv2.cvtColor(hsvnew, cv2.COLOR_HSV2BGR)

# save result
cv2.imwrite('bird_hue_changed.png', result)

cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result for hue shifted by 85:

enter image description here

fmw42
  • 46,825
  • 10
  • 62
  • 80