Skip to content

Instantly share code, notes, and snippets.

@madebyollin
Last active February 10, 2024 02:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madebyollin/4ad0964292449c4e21368003cf9401f7 to your computer and use it in GitHub Desktop.
Save madebyollin/4ad0964292449c4e21368003cf9401f7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import numpy as np
import cv2
from scipy.signal import convolve2d
from skimage import color, data, restoration
import console
# read input
frame = cv2.imread("input.jpg").astype(np.float32) / 255.0
# construct a 5x5 box blur kernel
psf = np.ones((5,5)) / 25
# convolve each channel with the kernel
for i in range(frame.shape[-1]):
frame[:,:,i] = convolve2d(frame[:,:,i], psf, mode="same")
# add gaussian noise
frame += 0.1 * frame.std() * np.random.standard_normal(frame.shape)
# wiener deconv
fixed = np.zeros(frame.shape)
for i in range(frame.shape[-1]):
fixed[:,:,i], _ = restoration.unsupervised_wiener(frame[:,:,i], psf)
# save output
fixed = np.clip(fixed * 255.0,0,255).astype(np.uint8)
cv2.imwrite("output.jpg", fixed)
@actual-kwarter
Copy link

actual-kwarter commented Jul 27, 2018

frame = frame.astype(np.float32)
for i in range(frame.shape[-1]):
    frame[:,:,i] = convolve2d(frame[:,:,i], psf, mode='same')
frame += 0.1 * frame.std() * np.random.standard_normal(frame.shape)
fixed = skimage.restoration.unsupervised_wiener(frame, psf)

This is what I did, and it still throws the ValueError.

@madebyollin
Copy link
Author

Try replacing:

fixed = skimage.restoration.unsupervised_wiener(frame, psf)

With:

fixed = np.zeros(frame.shape)
for i in range(frame.shape[-1]):
    fixed[:,:,i] = skimage.restoration.unsupervised_wiener(frame[:,:,i], psf)

@actual-kwarter
Copy link

If I do that, I get this back:
fixed[:,:,i] = skimage.restoration.unsupervised_wiener(frame[:,:,i], psf)
ValueError: could not broadcast input array from shape (2) into shape (1080,1920)

@madebyollin
Copy link
Author

Ah, oops, I forgot that it returns two values. You can fix that as follows (referencing this example http://scikit-image.org/docs/0.10.x/auto_examples/plot_restoration.html):

fixed = np.zeros(frame.shape)
for i in range(frame.shape[-1]):
    fixed[:,:,i], _ = skimage.restoration.unsupervised_wiener(frame[:,:,i], psf)

@madebyollin
Copy link
Author

I've updated the original post to be a working example including deconvolution.

@actual-kwarter
Copy link

Thank you so much. Can you please add your snippet as an answer on StackOverflow so I can mark it as a solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment