-1

我正在使用 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()

4

1 回答 1

1

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

在while循环内,有一行

k = cv.waitKey(0) & 0xFF

将其更改为:

k = cv.waitKey(1) & 0xFF

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

于 2021-08-15T06:56:20.583 回答