Trying to Plot FFT for an Image Array - python

I'm trying to create a signal plot for an array of pictures using the following code:
import numpy as np
import sys
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
imgArr = {}
stnArr = {}
frmArr = {}
sgnArr = {}
for i in range(1,2397):
imgArr[i] = mpimg.imread("20210209_themis_rank"+ str(i)+ ".png")
stnArr[i] = np.mean([imgArr[i]]/std(imgArr[i]))
frmArr[i] = i
signal = np.fft.fft(imgArr[i])
for i in range(1,2397):
plt.plot(frmArr,np.abs(signal))
plt.show()
However, I keep on running into the following error. How can I get it to work?
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (1,) and (600, 600, 4)

Related

I get the error module 'keygen' has no attribute 'keygen

I have also installed the appropriate libraries but still the error is showing. The code is written below:
import keygen as kg
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('Images/111.png')
plt.imshow(img)
#plt.show()
#Now generating the choatic Key
height = img.shape[0]
width = img.shape[1]
key = kg.keygen(0.01,3.951,height*width)
I get error at last line.
here keygen if a function not a library code for that function.
def keygen(x,r,size):
key = []
for i in range(size):
x = r*x*(1-x)
key.append(int((x*pow(10,16))%256))
return key

To fix an error : could not broadcast input array from shape (5,5) into shape (5,5,4)

I want to preprocess such an image dataset using an unsupervised wiener algorithm. But it doesn't work properly. when I run the code, it shows me a value attribute error. For convenience, my code is given below -
import cv2
import glob
from matplotlib import pyplot as plt
from skimage import io, restoration, img_as_float
import scipy.stats as st
import numpy as np
dataset = glob.glob('input/train/*.png')
directory = 'output/train/'
for img_id, img_path in enumerate(dataset):
img = img_as_float(io.imread(img_path))
def gkern(kernlen=21, nsig=2): #Returns a 2D Gaussian kernel.
lim = kernlen//2 + (kernlen % 2)/2
x = np.linspace(-lim, lim, kernlen+1)
kern1d = np.diff(st.norm.cdf(x))
kern2d = np.outer(kern1d, kern1d)
return kern2d/kern2d.sum()
psf = gkern(5,3) #Kernel length and sigma
deconvolved, _ = restoration.unsupervised_wiener(img, psf)
cl2 = cv2.resize(deconvolved, (512,512), interpolation = cv2.INTER_CUBIC)
plt.imsave(f"output/unsupervised_{img_id}.png", cl2, cmap='gray')
I am getting the error :
File "C:\Users\Junaed\.spyder-py3\unsupervised_wiener.py", line 33, in <module>
deconvolved, _ = restoration.unsupervised_wiener(img, psf)
ValueError: could not broadcast input array from shape (5,5) into shape (5,5,4)
How could I fix this issue, Can someone help me here?

Get a three dimensional array as a parameter and return a three dimensional arrays

I have to write a function to_red that should zero out the green and blue color components and return the result. I wrote the below code for an Image(.png) to zero out green and blue color and return red and it worked. However, as mentioned in title, the input parameter has to be a 3-d array and return a 3-d array. How should my below code be changed for that.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
def to_red()
src = plt.imread("C:\src\painting.png")
red_channel = src[:,:,0]
red_img = np.zeros(src.shape)
red_img[:,:,0] = red_channel
plt.imshow(red_img)
plt.show()
You can write your function like this:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
def to_red(src):
# Check if the input dimension is 3
if not src.ndim == 3:
# Raise exception or do something
print ("Dimension mismatch")
return 0
red_channel = src[:,:,0]
red_img = np.zeros(src.shape)
red_img[:,:,0] = red_channel
return red_img
And then you can call it like this
source_image = plt.imread("C:\src\painting.png")
red_image = to_red(source_image)
plt.imshow(red_image)
plt.show()
I also added a line to check if the input is actually 3 dimensional.
You can use numpy's powerful indexing capabilities
def to_red(src):
ret = a.copy()
ret[:,:,1:] = 0
return ret

ValueError: shape mismatch

I am trying K-means image compression, but I am getting this error
File "C:/Users/[user]/PycharmProjects/project/CompressMe.py", Line23, in <module>
final[pixel_centroids == cluster_no] = cluster_centers[cluster_no]
ValueError: shape mismatch: value array of shape (4,) could not be broadcast to indexing result of shape (267049,3)
My Code:
import numpy as np
from PIL import Image
from sklearn.cluster import KMeans
import matplotlib.pyplot as mpimg
import matplotlib.pyplot as plt
import os
img = Image.open('Capture.png')
img_np = np.asarray(img)
pixels = img_np.reshape(img_np.shape[0] * img_np.shape[1], img_np.shape[2])
model = KMeans(n_clusters = 32)
model.fit(pixels)
pixel_centroids = model.labels_
cluster_centers = model.cluster_centers_
final = np.zeros((pixel_centroids.shape[0], 3))
for cluster_no in range(32):
final[pixel_centroids == cluster_no] = cluster_centers[cluster_no]
comp_image = final.reshape(img_np.shape[0], img_np.shape[1], 3)
comp_image = Image.fromarray(np.uint8(comp_image))
comp_image.save('Capture_compressed.png')
img1 = mpimg.imread('Capture.png')
img2 = mpimg.imread('Capture_compressed.png')
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,20))
ax1.imshow(img1)
ax1.set_title('Original image')
ax2.imshow(img2)
ax2.set_title('Compressed image')
plt.show()
print('size of original image: ', int(os.stat('Capture.png').st_size / 1024), 'kB')
print('size of compressed image:', int(os.stat('Capture_compressed.png').st_size / 1024), 'kB')
You hardcoded the number of png output channels to 3, which could be different to the input, when you initialize the "final" array. Correct the following lines:
final = np.zeros((pixel_centroids.shape[0], img_np.shape[2]))
and
comp_image = final.reshape(img_np.shape[0], img_np.shape[1], img_np.shape[2])

Build a 3D array for 754 spectra

My problem is I have two arrays, one with my data (spectra), one is just filled up from 1 to 128 (1D arrays). I wonder how I can do to build a 3D array from these. I tried to use numpy.vstack but is seems that I have to precise in parameters the different arrays. I'm sure it's nothing complicated but I am a bit stuck right now. The idea is to build an array like this (and then to print the 3D curve) :
The goal is to have the right spectra when I move down the wavenumber. In 2D I have for instance :
With the following code :
import numpy as np
import array
import matplotlib.pyplot as plt
num_lon = 128
num_lat = 128
tmpfile = "180523_WT_striatum_#1.dat"
fileobj = open(tmpfile, mode='rb')
fileobj.seek(1020)
binvalues = array.array('f')
binvalues.read(fileobj, num_lon * num_lat)
data = np.array(binvalues)
data = np.reshape(data, (num_lat, num_lon))
L = [i for i in range(len(data))]
fileobj.close()
plt.plot(L,data[0])
plt.plot(L,data[1])
plt.show()
Do you guys have any lead ? Thank you very much.
import numpy as np
import array
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
num_lon = 128
num_lat = 754
tmpfile = "180523_WT_striatum_#1.dat"
fileobj = open(tmpfile, mode='rb')
fileobj.seek(1020)
binvalues = array.array('f') # 'f' stands for float 4 bytes
# It would be 'd' for float 8 bytes size
binvalues.read(fileobj, 128 * 128 )
data = np.array(binvalues)
data = np.reshape(data, (128,128))
L = np.array([[i for i in range(128)]for j in range(754)])
fileobj.close()
fig = plt.figure()
ax = fig.gca(projection='3d')
for i in range(len(data)):
ax.plot(L[i], data[i], i)
plt.show()

Categories