How to save the contour plot with .png format in python - save

I want to save contour in python. I can't do it very well.
I used plt.savefig() but image is empty.
why?
!pip install tftb
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
from tftb.generators import atoms
import tftb
import cv2
mat = sio.loadmat('/content/drive/MyDrive/z5_25.mat')
signal = mat['z']
z = signal.T
images_dir = '/content/drive/MyDrive/image'
for i in range(122):
wvd = tftb.processing.WignerVilleDistribution(z[i])
wvd.run()
fig = plt.figure()
plt.rcParams['figure.figsize']=(1.5,1.5)
wvd.plot(kind = 'contour')
plt.savefig(f"{images_dir}/fig5_25_{i}.png")
plt.show()

I know it is late but you can do so by replacing plt with wvd in the line
wvd.plot(kind = 'contour') plt.savefig(f"{images_dir}/fig5_25_{i}.png")
like this:
wvd.plot(kind = 'contour') wvd.savefig(f"{images_dir}/fig5_25_{i}.png")
it should work

Related

I want to use cv2_imshow in colab

import cv2 as cv
import numpy as np
from google.colab.patches import cv2_imshow
from tensorflow.keras.models import load_model
img_color = cv.imread('test3.jpg', cv.IMREAD_COLOR)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
ret,img_binary = cv.threshold(img_gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
kernel = cv.getStructuringElement( cv.MORPH_RECT, ( 5, 5 ) )
img_binary = cv.morphologyEx(img_binary, cv. MORPH_CLOSE, kernel)
cv2_imshow('digit', img_binary)
cv.waitKey(0)
This is the process of training a model in handwritten and testing the trained model.
I want to load an image using imshow() in colab.
Is there any way to use it without setting the file path?
You can use matplotlib's function for it
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.gcf()
fig.set_size_inches(18, 10)
plt.axis("off")
plt.rcParams['figure.figsize'] = [20, 10]
plt.imshow(img_binary)
plt.show()

How can I use "if __name__ == '__main__':" in my code below?

After I run my code I get a warning as:
"RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if name == 'main':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable."
My question is that how and where I should add this line of code to avoid this warning/error in my code below:
from scipy import stats, optimize
import pymc3 as pm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
#from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from theano import shared
np.random.seed(9)
#Load the Data
dataset = pd.read_csv(‘PV-PCM.csv’)
X=dataset.iloc[:,[0,1,2,3,4]].values
y=dataset.iloc[:,5].values
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size = 0.2, random_state=42)
#Shapes
X.shape, y.shape, X_tr.shape, X_te.shape
#Preprocess data for Modeling
shA_X = shared(X_tr)
#Generate Model
linear_model = pm.Model()
with linear_model:
# Priors for unknown model parameters
alpha = pm.Normal("alpha", mu=y_tr.mean(),sd=10)
betas = pm.Normal("betas", mu=0, sd=1000, shape=X.shape[1])
sigma = pm.HalfNormal("sigma", sd=100) # you could also try with a HalfCauchy that has longer/fatter tails
mu = alpha + pm.math.dot(betas, X_tr.T)
likelihood = pm.Normal("likelihood", mu=mu, sd=sigma, observed=y_tr)
step = pm.NUTS()
trace = pm.sample(1000, step)
chain = trace[100:]
#pm.traceplot(chain);
#Traceplot
pm.traceplot(trace)
ppc = pm.sample_prior_predictive(samples=1000, random_seed=9)
pm.plot_posterior(trace, figsize = (12, 10))
sns.kdeplot(y_tr, alpha=0.5, lw=4, c=‘b’)
for i in range(100):
sns.kdeplot(ppc[‘likelihood’][i], alpha=0.1, c=‘g’)
alpha_pred = chain[‘alpha’].mean()
betas_pred = chain[‘betas’].mean(axis=0)
y_pred = alpha_pred + np.dot(betas_pred, X_tr.T)
Thank you all.

I don't know opencv Error about code checking footsize

I want to make program checking my foot-size
I don't know this error about opencv
url: http://cocoding94.blogspot.com/2017/05/blog-post_7.html .
import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("foot.jpeg")
blur = cv2.blur(img,(5,10))
rows,cols,ch = img.shape
pts1 = np.float32([170,270],[480,220],[240, 710],[540,650])
pts2 = np.float32([0,0],[210,0],[0,297],[210,297])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(210,297))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.plot(*zip(*point), marker='.', color='r', ls='')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
In raspberry pi error printing:
Traceback (most recent call last): File "foot.py",line 7,in
blur = cv2. blur (img,(5,10)) cv2.error:OpenCV(3.4.3)
/home/pi/opencv/opencv-3.4.3/modules/core/src/matrix.cpp:756: error:
(-215:Assertion failed) dims <=2 && step[0] > 0 in function
'locateROI'
but please next time add more information to make this community greater than another, I fixed some errors in your code, i don´t your original image, but the code now works well, try to change your point to get a good perspective:
import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread("machupichu.jpg")
#blur = cv2.blur(img,(5,5))
#rows,cols,ch = img.shape
point=[[170,270],[480,220],[240, 710],[540,650]]
pts1 = np.float32([[170,270],[480,220],[240, 710],[540,650]])
pts2 = np.float32([[0,0],[210,0],[0,297],[210,297]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(210,297))
plt.subplot(121)
plt.imshow(img)
plt.title('Input')
plt.plot(*zip(*point), marker='.', color='r', ls='')
plt.subplot(122)
plt.imshow(dst)
plt.title('Output')
plt.show()
Here is the image which I used:
Machu Pichu
This is the result:
Best Regards.

Using an autoencoder to reduce dimensionality

Here is my version of an autoencoder written using PyTorch :
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import pyplot as plt
from sklearn import metrics
import datetime
from sklearn.preprocessing import MultiLabelBinarizer
import seaborn as sns
sns.set_style("darkgrid")
from ast import literal_eval
import numpy as np
from sklearn.preprocessing import scale
import seaborn as sns
sns.set_style("darkgrid")
import torch
%matplotlib inline
f = []
f.append(np.random.uniform(0,10,(1 , 10)).flatten())
f.append(np.random.uniform(10,20,(1 , 10)).flatten())
f.append(np.random.uniform(20,30,(1 , 10)).flatten())
x_data = torch.FloatTensor(np.array(f))
x_data
dimensions_input = 10
hidden_layer_nodes = 5
output_dimension = 10
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(dimensions_input,hidden_layer_nodes)
self.sigmoid = torch.nn.Sigmoid()
self.linear2 = torch.nn.Linear(hidden_layer_nodes,output_dimension)
def forward(self, x):
l_out1 = self.linear(x)
l_out2 = self.sigmoid(l_out1)
y_pred = self.linear2(l_out2)
return y_pred
model = Model()
criterion = torch.nn.MSELoss(size_average = False)
optim = torch.optim.SGD(model.parameters(), lr = 0.00001)
def train_model():
y_data = x_data.clone()
for i in range(150000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
if i % 5000 == 0:
print(loss)
optim.zero_grad()
loss.backward()
optim.step()
Using x_data.clone() I train the network to learn a feature representation of the input data.
I'm attempting to generate hidden layer weights that match the dimensionality of rows of the input data so that each vector of x_data has a corresponding encoding. But the hidden later is of is a vector of size 5. How to change this network so that a matrix is generated that represents a reduced dimensionality of the input data ?

Is it correct way to make a Dictionary by using Multiple Image?

I have written a code to make a Dictionary by using Multiple Image.
Here is my code =>
from time import time
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from sklearn.decomposition import MiniBatchDictionaryLearning
from sklearn.feature_extraction.image import extract_patches_2d
from sklearn.feature_extraction.image import reconstruct_from_patches_2d
from sklearn.utils.fixes import sp_version
from sklearn.datasets import load_sample_image
from scipy import ndimage
from skimage import color
from skimage import io
from PIL import Image
from sklearn.decomposition import SparseCoder
from sklearn.decomposition import sparse_encode
from scipy.misc import imfilter, imread
from scipy.signal import convolve2d as conv2
from skimage import data, img_as_float
from scipy import ndimage as ndi
from skimage import feature
from scipy.misc import imsave
c = np.asarray(Image.open('047.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
d = np.asarray(Image.open('048.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
e = np.asarray(Image.open('049.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
f = np.asarray(Image.open('046.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
g = np.asarray(Image.open('038.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
h = np.asarray(Image.open('039.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
n0 = np.asarray(Image.open('037.jpg').convert('L').resize((512,512), Image.ANTIALIAS))
n0 = n0 / 255
height, width = n0.shape
n0 = n0 + 0.075 * np.random.randn(height, width)
imsave('noise.png',n0)
patchsize = (8,8)
t0 = time()
data1 = extract_patches_2d(c,(8,8))
data2 = extract_patches_2d(d,(8,8))
data3 = extract_patches_2d(e,(8,8))
data4 = extract_patches_2d(f,(8,8))
data5 = extract_patches_2d(g,(8,8))
data6 = extract_patches_2d(h,(8,8))
data = np.append(data1,data2,axis=0)
data = np.append(data,data3,axis=0)
data = np.append(data,data4,axis=0)
data = np.append(data,data5,axis=0)
data = np.append(data,data6,axis=0)
data = data.reshape(data.shape[0], -1)
print('Extract patch shape :',data.shape)
data = data - np.mean(data, axis=0)
data = data / np.std(data, axis=0)
t1 = time()
print('Total time : ',round((t1-t0),2),' sec')
print('Learning the dictionary ....')
t2 = time()
n_iter = 1000
dico = MiniBatchDictionaryLearning(n_components=100,alpha=3,n_iter=n_iter)
V = dico.fit(data).components_
Actually I want to train a well learned Dictionary that will help me to denoise an Image.
Is it correct way to train a dictionary By using Multiple Image?

Resources