0

When I apply a median filter in a gray image it gets converted back to a RGB image. Why?

See code below:

path = '/content/img_gray' # Source Folder
dstpath = '/content/img_filtered_gray' # Destination Folder
try:
    makedirs(dstpath)
except:
    print ("Directory already exist, images will be written in same folder")
# Folder won't used
files = list(filter(lambda f: isfile(join(path,f)), listdir(path)))
for image in files:
    try:
        img = cv2.imread(os.path.join(path,image))
        median = cv2.medianBlur(img,5)
        dstPath = join(dstpath,image)
        cv2.imwrite(dstPath,median)
    except:
        print ("{} is not converted".format(image))
nitin
  • 1
  • How did you determine that the input image was grayscale and the output image is RGB? – mkrieger1 Apr 04 '21 at 22:37
  • 1
    Does this answer your question? [In OpenCV (Python), why am I getting 3 channel images from a grayscale image?](https://stackoverflow.com/questions/18870603/in-opencv-python-why-am-i-getting-3-channel-images-from-a-grayscale-image) – mkrieger1 Apr 04 '21 at 22:40
  • can you add the input image and output image or shape of the input image and output image – Kukesh Apr 07 '21 at 08:41

1 Answers1

0

Convert to Gray from BGR before you apply medianBlur:

img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
median = cv2.medianBlur(img,5)

Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed).

Anurag Dhadse
  • 1,722
  • 1
  • 13
  • 26