CodeMaster
CodeMaster

Reputation: 449

Applying gaussian blur to images in a loop

I have a simple ndarray with shape as:

import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(trainImg[0])  #can display a sample image
print(trainImg.shape) : (4750, 128, 128, 3)  #shape of the dataset

I intend to apply Gaussian blur to all the images. The for loop I went with:

trainImg_New = np.empty((4750, 128, 128,3)) 
for idx, img in enumerate(trainImg):
  trainImg_New[idx] = cv2.GaussianBlur(img, (5, 5), 0)

I tried to display a sample blurred image as:

plt.imshow(trainImg_New[0])  #view a sample blurred image

but I get an error:

Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).

It just displays a blank image.

Upvotes: 0

Views: 1386

Answers (2)

V Demo
V Demo

Reputation: 151

TL;DR: The error is most likely caused by trainImg_New is float datatype and its value is larger than 1. So, as @Frightera mentioned, try using np.uint8 to convert images' datatype.

I tested the snippets as below:

import numpy as np
import matplotlib.pyplot as plt
import cv2

trainImg_New = np.random.rand(4750, 128, 128,3) # all value is in range [0, 1]
save = np.empty((4750, 128, 128,3))
for idx, img in enumerate(trainImg_New):
  save[idx] = cv2.GaussianBlur(img, (5, 5), 0)

plt.imshow(np.float32(save[0]+255)) # Reported error as question
plt.imshow(np.float32(save[0]+10)) # Reported error as question
plt.imshow(np.uint8(save[0]+10)) # Good to go

First of all, cv2.GaussianBlur will not change the range of the arrays' value and the original image arrays's value is legitimate. So I believe the only reason is the datatype of the trainImg_New[0] is not match its range.

So I tested the snippets above, we can see when the datatype of trainImg_New[0] matter the available range of the arrays' value.

Upvotes: 1

Nicolas Gervais
Nicolas Gervais

Reputation: 36614

I suggest you use tfa.image.gaussian_filter2d from the tensorflow_addons package. I think you'll be able to pass all your images at once.

import tensorflow as tf
from skimage import data
import tensorflow_addons as tfa
import matplotlib.pyplot as plt

image = data.astronaut()

plt.imshow(image)
plt.show()

enter image description here

blurred = tfa.image.gaussian_filter2d(image, 
                                      filter_shape=(25, 25), 
                                      sigma=3.)

plt.imshow(blurred)
plt.show()

enter image description here

Upvotes: 1

Related Questions