# Apply Filter as a part of preprocessing

**URL:** <https://discuss.pytorch.org/t/apply-filter-as-a-part-of-preprocessing/115329>\
**Category:** Uncategorized\
**Created:** [March 19, 2021, 10:44am UTC](https://discuss.pytorch.org/t/apply-filter-as-a-part-of-preprocessing/115329 "2021-03-19T10:44:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kapil\_Rana](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/kapil_rana/32/20951_2.png) [@Kapil\_Rana](https://discuss.pytorch.org/u/Kapil_Rana)\
**Post date:** [March 19, 2021, 10:44am UTC](https://discuss.pytorch.org/t/apply-filter-as-a-part-of-preprocessing/115329/1 "2021-03-19T10:44:01Z")

</div>

Hello,

I want to apply a custom 5x5 filter on image as a part of preprocessing.

Can someone suggest me code.

I have already done  
def HPF(img):  
image = np.array(img)  
kernel = np.array([[1,4,7,4,1],  
[4,16,26,16,4],  
[7,26,41,26,7],  
[4,16,26,16,4],  
[1,4,7,4,1]])  
kernel = kernel/273  
img\_rst = cv2.filter2D(np.float32(image),-1,kernel)  
new\_image = img\_rst  
return new\_image

x = Image.open("/home/iit/Kapil/Code/DIP/lenna.jpg").convert(‘RGB’)  
#img = TF.to\_pil\_image(x)  
transform = transforms.Lambda(HPF)  
img = transform(x)

but it does not do any kind of blurring (Gaussian Blurr)

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [March 20, 2021, 6:37am UTC](https://discuss.pytorch.org/t/apply-filter-as-a-part-of-preprocessing/115329/2 "2021-03-20T06:37:35Z")

</div>

Your method works fine using random inputs:

```python
def HPF(img):
    image = np.array(img)
    kernel = np.array(
        [[1,4,7,4,1],
         [4,16,26,16,4],
         [7,26,41,26,7],
         [4,16,26,16,4],
         [1,4,7,4,1]])
    kernel = kernel/273
    img_rst = cv2.filter2D(np.float32(image),-1,kernel)
    new_image = img_rst
    return new_image

x = PIL.Image.fromarray(np.random.uniform(0, 256, (224, 224, 3)).astype(np.uint8))

transform = transforms.Lambda(HPF)
img = transform(x)

plt.imshow(img.astype(np.uint8))

```
