Generate hp filtered phase randomized image

Hello,

I wanted to ask advice on how to generate high pass filtered phase randomized image. I used psychopy spatial filtering example as a starting point.

The problem that generated scrambled image seems to have some sort of pattern. I am not sure whether I did it in a proper way. It would be great if someone could take a look and give me some feedback.

Thanks,

hp_filteredrandom_phaseraw

path = r"natural_images\005.tif"

# this gives a (y, x) array of values between 0.0 and 255.0
img = Image.open(path)

maxsize = (1600, 1200)
# convert to grayscale
img = img.convert('L')
# resize to the fullscreen
img = img.resize(maxsize, Image.ANTIALIAS)
# convert to array
img = np.array(img)
# rescale to -1 +1
img = (img / 255.0) * 2.0 - 1.0
# invert image
img = np.flipud(img)


img_freq = np.fft.fft2(raw_img)
# calculate amplitude spectrum
img_amp = np.fft.fftshift(np.abs(img_freq))
# extract phase information
img_phase = np.angle(img_freq)

hp_filt = filters.butter2d_hp(
    size=raw_img.shape,
    cutoff= 0.0041667,
    n=10
)

img_filt = np.fft.fftshift(img_freq) * hp_filt

img_new = np.real(np.fft.ifft2(np.fft.ifftshift(img_filt)))

# generate phase scrambled image
noise = (np.random.choice( [0,1], [img.shape[0], img.shape[1]])*2 -1)/2
noise_freq = (np.fft.fft2(noise))
hp_noise = np.fft.fftshift(noise_freq) * hp_filt
rand_phase = np.angle(np.fft.ifftshift(hp_noise))

#image with scrambled phase
scrambled_image = np.abs(np.fft.ifftshift(img_filt))*np.exp(1j*rand_phase)
scrambled_image = np.real(np.fft.ifft2((scrambled_image)))
1 Like

I tend to do it something like:

img_fft = np.fft.fft2(img)

img_amp = np.abs(img_fft) * np.fft.ifftshift(hp_filt)

img_phase = np.angle(np.fft.fft2(np.random.rand(*img.shape)))

scrambled_img = np.fft.ifft2(
    img_amp * np.cos(img_phase) +
    1j * (img_amp * np.sin(img_phase))
)

scrambled_img = np.real(scrambled_img)

Hello,

Thanks for sharing your code. I just wanted to ask what is the reasoning to vary phase as sin/cos?

Thanks,

It’s to convert from the polar representation (amplitude, phase) into the rectangular components for the inverse FFT.