opencv 使用Python在网络摄像头镜头上实现色调循环效果

iecba09b  于 2023-01-09  发布在  Python
关注(0)|答案(1)|浏览(159)

我正在尝试用Python创建一个程序,它可以检索摄像头镜头,并应用一个缓慢而恒定的色调变化,类似于色调循环效果。另外,我想知道是否有可能只对摄像头镜头中的绿色应用色调循环,尽管我不确定如何检测帧中的颜色并只对该颜色应用循环。
我试着玩这个代码我发现,虽然它得到适用于整个帧和输出在某些斑点变色/奇怪的斑点取决于它是对循环的一部分。

import cv2
import numpy as np

# Initialize video capturer
cap = cv2.VideoCapture(0)

# Set frame width and height
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Initialize angle for hue rotation
angle = 0

while True:
    # Capture frame
    ret, frame = cap.read()

    # Convert frame to HSV color space
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # Split channels
    h, s, v = cv2.split(hsv)

    # Increment angle
    angle = (angle + 1) % 360

    # Rotate hue channel
    h = (h + angle) % 180

    # Merge channels back to HSV image
    hsv = cv2.merge((h, s, v))

    # Convert back to BGR color space
    result = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

    # Display frame
    cv2.imshow("Webcam", result)

    # Check for user input
    key = cv2.waitKey(1)
    if key == 27: # Esc key
        break

# Release video capturer
cap.release()

# Close all windows
cv2.destroyAllWindows()
gopyfrb3

gopyfrb31#

您可以使用颜色阈值和蒙版检测帧中的绿色。要检测绿色,请尝试inRange函数:

import cv2
import numpy as np

# Initialize video capturer
cap = cv2.VideoCapture(0)

# Set frame width and height
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Initialize angle for hue rotation
angle = 0

while True:
    # Capture frame
    ret, frame = cap.read()

    # Convert frame to HSV color space
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # Split channels
    h, s, v = cv2.split(hsv)

    # Define lower and upper bounds for green color
    lower_green = np.array([50, 50, 50])
    upper_green = np.array([70, 255, 255])

    # Create mask for green color
    mask = cv2.inRange(hsv, lower_green, upper_green)

    # Increment angle
    angle = (angle + 1) % 360

    # Rotate hue channel only for green pixels
    h[mask != 0] = (h[mask != 0] + angle) % 180

    # Merge channels back to HSV image
    hsv = cv2.merge((h, s, v))

    # Convert back to BGR color space
    result = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

    # Display frame
    cv2.imshow("Webcam", result)

    # Check for user input
    key = cv2.waitKey(1)
    if key == 27: # Esc key
        break

# Release video capturer
cap.release()

# Close all windows
cv2.destroyAllWindows()

相关问题