-1

I am creating a trackbar using python OpenCV and then changing the color of the image by changing the BGR value. when I run the code to trackbar gets displayed and when I change the value of BGR I will get only value but color of the image remains black.

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

the code is running without any error but after running when i try to change the BGR values the color doesn't change. i am learning from this tutorial (YouTube) - https://www.youtube.com/watch?v=fM6ff3VEviI&list=PLS1QulWo1RIa7D1O6skqDQ-JZ1GGHKK-K&index=13.

I also tried adding the switch trackbar but color is not changing even after changing the color to 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()
Community
  • 1
  • 1

1 Answers1

1

In your first code, everything is good except a digit.

Inside the while loop, there's the line

k = cv.waitKey(0) & 0xFF

Change it to:

k = cv.waitKey(1) & 0xFF

The reason being the value of num in waitKey(num) determines how much time the code will have to stop to read the keyboard value. When num = 0, the code will stop forever until some key is pressed.

Rahul Kedia
  • 1,400
  • 6
  • 18