python opencv如何改变HSV通道的色调

2023-12-23

如何通过动态hue_offset改变hue通道的值来实现img_update(hue_offset)函数。实现img_update(hue_offset)函数,实现此提交:1.通过动态hue_offset更改色调通道的值。

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()

这是在 Python/OpenCV 中实现此目的的一种方法。

Input:

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()

色调偏移 85 的结果:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python opencv如何改变HSV通道的色调 的相关文章

随机推荐