gpt4 book ai didi

python - 如何通过调整 RGB 值来编写自定义灰度滤镜?

转载 作者:行者123 更新时间:2023-12-02 17:18:01 26 4
gpt4 key购买 nike

我正在尝试创建一个灰度滤镜,允许您调整图像中所有像素的 RGB 百分比,例如(红色=20%、绿色=70%、蓝色=10%)。我宁愿这样做是基本级别,所以转换量最少,只需使用公式来允许这种情况发生。
我会假设代码看起来很像这样:

import numpy as np
import cv2
img=cv2.imread(filepath)
imgBlue=img[:,:,0]
imgGreen=[:,:,1]
imgRed=[:,:,2]
blueCon=imgBlue*.1
greenCon=imgGreen*.7
redCon=imgRed*.2
greyscaledImg=img[:,:,:]
greyscaledImg[:,:,0]=blueCon
greyscaledImg[:,:,1]=greenCon
greyscaledImg[:,:,2]=redCon
cv2.imwrite(filepath,greyscaledImg)

最佳答案

这可能是使用 OpenCV 的轨迹栏的一个很好的例子,见 this example .
但是,我认为灰度过滤器的提议概念不会那样工作,因为你只是线性缩放整个图像的 RGB 值。要获得灰色调,您需要单独处理图像中的所有像素。
不过,这是您在上面示例中构建的概念:

import cv2

# Setup maximum factors for each channel
r_max = 100
g_max = 100
b_max = 100

# Window title
title_window = 'Custom gray scale'


# Event for R trackbar change
def on_r_trackbar(val):
dst[:, :, 2] = val / r_max * src[:, :, 2]
cv2.imshow(title_window, dst)


# Event for G trackbar change
def on_g_trackbar(val):
dst[:, :, 1] = val / g_max * src[:, :, 1]
cv2.imshow(title_window, dst)


# Event for B trackbar change
def on_b_trackbar(val):
dst[:, :, 0] = val / b_max * src[:, :, 0]
cv2.imshow(title_window, dst)


# Read some input image
src = cv2.imread('path/to/your/image.png')
dst = src.copy()

# Setup window and create trackbars for each channel
cv2.namedWindow(title_window)
cv2.createTrackbar('R', title_window, 100, r_max, on_r_trackbar)
cv2.createTrackbar('G', title_window, 100, g_max, on_g_trackbar)
cv2.createTrackbar('B', title_window, 100, b_max, on_b_trackbar)

# Show something, and wait until user presses some key
cv2.imshow(title_window, dst)
cv2.waitKey()
这就是窗口最初的样子:
1
并且,设置你的值(value)观,给出:
2
因此,为了获得一些灰色的外观,我会坚持使用 HSV color space ,并简单地修改饱和 channel :
import cv2

# Setup maximum factor for the saturation
s_max = 100

# Window title
title_window = 'Custom gray scale'


# Event for S (saturation) trackbar change
def on_s_trackbar(val):
dst[:, :, 1] = val / s_max * hsv[:, :, 1]
cv2.imshow(title_window, cv2.cvtColor(dst, cv2.COLOR_HSV2BGR))


# Read some input image, and convert to HSV color space
src = cv2.imread('path/to/your/image.png')
hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
dst = hsv.copy()

# Setup window and create trackbar for the S (saturation) channel
cv2.namedWindow(title_window)
cv2.createTrackbar('S', title_window, 100, s_max, on_s_trackbar)

# Show something, and wait until user presses some key
cv2.imshow(title_window, cv2.cvtColor(dst, cv2.COLOR_HSV2BGR))
cv2.waitKey()
同样,在初始窗口中,只剩下一个用于饱和的轨迹栏:
3
并且,饱和度的一些调整给出:
4
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
OpenCV: 4.4.0
----------------------------------------

关于python - 如何通过调整 RGB 值来编写自定义灰度滤镜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63735195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com