【问题标题】:opencv (getTrackbarPos) color is not changing in image only the value is changingopencv(getTrackbarPos)颜色在图像中没有变化,只有值在变化
【发布时间】:2021-10-17 15:30:41
【问题描述】:

我正在使用 python OpenCV 创建一个轨迹栏,然后通过更改 BGR 值来更改图像的颜色。当我运行代码以显示轨迹栏时,当我更改 BGR 的值时,我只会得到值,但图像的颜色仍然是黑色。

import numpy as np 
import cv2 as cv 

def nothing(x):
    print(x)

img =  np.zeros((300,512,3), np.uint8) # creating a black image
cv.namedWindow('image') # creating a window 

cv.createTrackbar('B', 'image', 0, 255, nothing)  # add trackbar to image
cv.createTrackbar('G', 'image', 0, 255, nothing)
cv.createTrackbar('R', 'image', 0, 255, nothing)

while(1):
    cv.imshow('image', img) # show the image
    k = cv.waitKey(0) & 0xFF # checks the input - esc key 
    if k == 27:
        break
    
    b = cv.getTrackbarPos('B', 'image') # get the position value of b 
    g = cv.getTrackbarPos('G', 'image') # get the position value of g
    r = cv.getTrackbarPos('R', 'image') # get the position value of r
     
    img[:] = [b, g, r]
 
cv.destroyAllWindow()

代码运行时没有任何错误,但运行后我尝试更改 BGR 值时颜色不会改变。我正在学习本教程 (YouTube) - https://www.youtube.com/watch?v=fM6ff3VEviI&list=PLS1QulWo1RIa7D1O6skqDQ-JZ1GGHKK-K&index=13

我也尝试添加切换轨迹栏,但即使将颜色更改为 1,颜色也不会改变

import numpy as np 
import cv2 as cv 

def nothing(x):
    print(x)

img =  np.zeros((300,512,3), np.uint8) # creating a black image
cv.namedWindow('image') # creating a window 

cv.createTrackbar('B', 'image', 0, 255, nothing)  # add trackbar to image
cv.createTrackbar('G', 'image', 0, 255, nothing)
cv.createTrackbar('R', 'image', 0, 255, nothing)

switch = '0 : OFF\n 1: ON'
cv.createTrackbar(switch, 'image', 0, 1, nothing)

while(1):
    cv.imshow('image', img) # show the image
    k = cv.waitKey(0) & 0xFF # checks the input - esc key 
    if k == 27:
        break
    
    b = cv.getTrackbarPos('B', 'image') # get the position value of b 
    g = cv.getTrackbarPos('G', 'image') # get the position value of g
    r = cv.getTrackbarPos('R', 'image') # get the position value of r
    s = cv.getTrackbarPos(switch, 'image')

    if s ==0:
        img[:] = 0 
    else : 
        img[:] = [b, g, r]
 
cv.destroyAllWindow()

【问题讨论】:

    标签: opencv colors opencv-python trackbar bgr


    【解决方案1】:

    在您的第一个代码中,除了一个数字之外,一切都很好。

    在while循环里面,有一行

    k = cv.waitKey(0) & 0xFF
    

    改成:

    k = cv.waitKey(1) & 0xFF
    

    waitKey(num)num 的值决定了代码必须停止多少时间才能读取键盘值。当num = 0 时,代码将永远停止,直到按下某个键。

    【讨论】:

    • 我认为这个答案行不通。所以+1 :)
    猜你喜欢
    • 2012-11-25
    • 2017-04-11
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2021-02-10
    • 2014-07-07
    相关资源
    最近更新 更多