can you please convert python code to matlab code for image processing ?
5 views (last 30 days)
Show older comments
# -*- coding: utf-8 -*- """
""" #import required libraries import numpy as np from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from keras.utils import np_utils from keras.layers import Conv2D, Input, Dropout from keras.models import Model from keras.layers.pooling import MaxPooling2D from keras.layers.core import Flatten, Dense from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint import pickle import cv2 import time import os #reading images def load_images(folder): images = [] for filename in os.listdir(folder): img = cv2.imread(os.path.join(folder, filename)) if img is not None: img = cv2.resize(img, (80,80)) images.append(img) return np.array(images) #storing images benign = load_images('./lung_colon_image_set/lung_image_sets/lung_n/') mal_aca = load_images('./lung_colon_image_set/lung_image_sets/lung_aca/') mal_scc = load_images('./lung_colon_image_set/lung_image_sets/lung_scc/') #images shape after resizing print(f"Images shape: {benign[0].shape}.") indices = [0, 40, 2300] plt.figure(1, figsize=(15,5)) plt.grid(None) for n, idx in enumerate(indices): plt.subplot(n+1, 3, 1) plt.imshow(benign[idx]) plt.title('benign') plt.subplot(n+1, 3, 2) plt.imshow(mal_aca[idx]) plt.title('malignant aca') plt.subplot(n+1, 3, 3) plt.imshow(mal_scc[idx]) plt.title('malignant scc') #plotting sample input image plt.show() #concatenate images and create labels samples = np.concatenate((benign, mal_aca, mal_scc)) labels = np.array(benign.shape[0] * [0] + mal_aca.shape[0] * [1] + mal_scc.shape[0] * [2]) #shuffling randomly indices = np.arange(samples.shape[0]) np.random.shuffle(indices) samples = samples[indices] labels = labels[indices] # normalize pictures samples = samples.astype('float32') / 255 #splitting data into train and test X_train, X_test, y_train, y_test = train_test_split(samples, labels, test_size = 0.2) X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size = 0.5) Y_train = np_utils.to_categorical(y_train, 3) Y_val = np_utils.to_categorical(y_val, 3) Y_test = np_utils.to_categorical(y_test, 3) #creating model def base_model(input_shape=(80,80,3), classes=3): inputs = Input(shape=input_shape) X = Conv2D(32, 3, 3, activation='relu')(inputs) X = MaxPooling2D(pool_size=(2,2))(X) X = Conv2D(64, 3, 3, activation='relu')(X) X = MaxPooling2D(pool_size=(2,2))(X) X = Dropout(0.2)(X) X = Conv2D(128, 3, 3, activation='relu', padding='same')(X) X = MaxPooling2D(pool_size=(2,2), padding='same')(X) X = Dropout(0.2)(X) X = Flatten()(X) X = Dense(256, activation='relu')(X) outputs = Dense(classes, activation='softmax')(X) model = Model(inputs, outputs, name='DetectionModel') return model model = base_model(input_shape=(80,80,3), classes=3) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics='accuracy') checkpoint = ModelCheckpoint("modelsave.h5", monitor='val_accuracy', verbose=1, save_best_only=True, mode='max') history = model.fit(X_train, Y_train, batch_size=64, epochs=35, validation_data=(X_val, Y_val), callbacks=[checkpoint]) #plotting loss and accuracy graph plt.style.use('seaborn') plt.figure(figsize=(16,7)) plt.subplot(1,2,1) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss', fontsize=16) plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['train', 'val']) plt.subplot(1,2,2) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy', fontsize=16) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['train', 'val']) plt.show() from sklearn.metrics import confusion_matrix import seaborn as sn y_pred_test = model.predict(X_test, verbose=1) y_pred_train = model.predict(X_train, verbose=1) y_pred_test = np.argmax(y_pred_test, axis=1) y_pred_train = np.argmax(y_pred_train, axis=1) #evaluating model on test dataset score_test = model.evaluate(X_test, Y_test) print(f"Train accuracy: {history.history['accuracy'][-1]:.3f}") print(f"Validation accuracy: {history.history['val_accuracy'][-1]:.3f}") print(f"Test accuracy: {score_test[1]:.3f}") label_names = ['benign', 'mal_aca', 'mal_scc'] #confusion matrix confmat = confusion_matrix(y_train, y_pred_train) sn.heatmap(confmat, annot=True, cmap='Blues', cbar=False, xticklabels=label_names, yticklabels=label_names)
0 Comments
Answers (1)
Sivylla Paraskevopoulou
on 31 May 2022
Save the TensorFlow model that you created in the SavedModel format, and then you can import the TensorFlow model into MATLAB by using the importTensorFlowNetworkNetwork function.
For an example on how to compare the image classification results between your TensorFlow model and the imported MATLAB network, see Inference Comparison Between TensorFlow and Imported Networks for Image Classification.
0 Comments
See Also
Categories
Find more on Pretrained Networks from External Platforms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!