Search code examples
pythonimage-processingopencvtrackbar

Use cv2.createTrackbar to blur images using python


I tried the following code:

import cv2
import numpy as np

   
def nothing(x):
  pass

cv2.namedWindow('Image')
img = cv2.imread("kakashi.jpg")

low = 1
high = 100

cv2.createTrackbar('Blur', 'Image',low,high,nothing)
while (True):
    ksize = cv2.getTrackbarPos('ksize', 'Image')
    ksize = -2*ksize-1
    image = cv2.medianBlur(img,ksize)
    
    cv2.imshow('Image', image)
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

By changing the position of the slider there are no effects on the image. I am having trouble solving this. I guess there is something I am missing! Please help!


Solution

  • There is a simple mistake, you are doing. You defined your trackbar name in here as "Blur":

    cv2.createTrackbar('Blur', 'Image',low,high,nothing)
    

    Then you are calling your trackbar as "ksize"

    ksize = cv2.getTrackbarPos('ksize', 'Image')
    

    which is wrong so if you simply change this line with this one:

    ksize = cv2.getTrackbarPos('Blur', 'Image')
    

    it will fix.

    Note: As @fmw42 mentioned in comments, there are also some problems about median size you are calculating. You may recheck it.