I have been working on this image classification(watermark detection) assignment
I am trying to load a folder of images
from keras.preprocessing.image import load_img
import cv2
import matplotlib.pyplot as plt
DATADIR = 'F:\IMP.DATA\Task\Watermark_test_data'
CATEGORIES=['Watermark','No Watermark']
for category in CATEGORIES:
path= os.path.join(DATADIR,category)#path to test folder
for img in os.listdir(path):
img_array = cv2.imread(os.path.dirname(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
plt.imshow(img_array,cmap="gray")
plt.show(img_array)
break
break
img = load_img('F:/IMP.DATA/Task/Watermark_test_data/Watermark/1.jpg')
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
img.show()
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten
from keras.layers.convolutional import Conv2D,MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
import os
import cv2
DATADIR = 'F:\IMP.DATA\Task\Watermark_test_data'
CATEGORIES=['Watermark','No Watermark']
for category in CATEGORIES:
path= os.path.join(DATADIR,category)#path to test folder
for img in os.listdir(path):
img_array = cv2.imread(os.path.dirname(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
plt.imshow(img_array,cmap="gray")
plt.show(img_array)
break
break
I have been using cv2 and load_img to load the image but in both the cases I get error in matplotlib
plt.imshow (function)
This is the error that I get
File "<ipython-input-51-2b07cb64d5a1>", line 11
plt.imshow(img_array,cmap="gray")
^
SyntaxError: invalid syntax
I can't see anything wrong in the syntax
The SyntaxError is caused by a missing closing parenthesis in this line:
img_array = cv2.imread(os.path.dirname(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
Add ) after os.path.dirname(os.path.join(path,img) to solve it.
Related
pip install -q hvplot
import pandas as pd
import numpy as np
import seaborn as sns
from scipy import stats
import matplotlib.pyplot as plt
import hvplot.pandas
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import (
accuracy_score, confusion_matrix, classification_report,
roc_auc_score, roc_curve, auc,
plot_confusion_matrix, plot_roc_curve
)
from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import AUC
pd.set_option('display.float', '{:.2f}'.format)
pd.set_option('display.max_columns', 50)
pd.set_option('display.max_rows', 50)
I'm trying to run a code from Kaggle.
https://www.kaggle.com/code/faressayah/lending-club-loan-defaulters-prediction
However, I was stuck in the first few steps, which are the code lines above. I've spent hours on this and can't figure it out. I got the following error message
Does anyone know how to fix this? Thank you very much for helping out!
I am working in colab to test a code. While importing models, its giving error No module named 'efficientnet'
I am sharing the code and error here.
# for accessing tabular data
import pandas as pd
import numpy as np
import os
os.chdir('/content/drive/My Drive/')
# adding classweight
from sklearn.utils import class_weight
# Evaluation Metric
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import confusion_matrix, precision_score, recall_score
# for visualization
import cv2
import matplotlib.pyplot as plt
import seaborn as sns
from prettytable import PrettyTable
# backend
import keras
from keras import backend as K
import tensorflow as tf
from keras.callbacks import Callback
# for transfer learning
from tensorflow.keras.applications import VGG16, VGG19
from tensorflow.keras.applications import DenseNet121
from tensorflow.keras.applications import ResNet50, ResNet152
from tensorflow.keras.applications import InceptionV3
from efficientnet.keras import EfficientNetB0, EfficientNetB3, EfficientNetB4
from keras.applications import Xception
# for model architecture
from keras.models import Sequential
from keras.layers import GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Activation, Flatten
# for Tensorboard visualization
from keras.callbacks import TensorBoard
# for Data Augmentation
from keras.preprocessing.image import ImageDataGenerator
enter image description here
It should be,
from tensorflow.keras.applications import EfficientNetB0, EfficientNetB3, EfficientNetB4
I'm working on a webapp for a machine learning project using Streamlit.
I've encountered this error at load_img:
TypeError: expected str, bytes or os.PathLike object, not UploadedFile.
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.applications.vgg16 import decode_predictions
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import model_from_json
import numpy as np
import cv2
import tensorflow as tf
import streamlit as st
st.write("This is a simple image classification web app to identify cars")
file = st.file_uploader("Please upload an image file", type=["jpg", "png"])
def import_and_predict(image_data, model):
image = load_img(image_data,target_size=(64,64))
img = img_to_array(image)
img = np.array(image)
img = img / 255.0
image = img.resize((64,64))
img = img.reshape(1,64,64,3)
label = model.predict_classes(img)
prediction = label[0][0]
return f"Prediction: {prediction}"
if file is None:
st.text("Please upload an image file")
else:
import_and_predict(file, model)
From the Streamlit documentation for file_uploader:
>>> uploaded_file = st.file_uploader("Choose a file")
>>> if uploaded_file is not None:
... # To read file as bytes:
... bytes_data = uploaded_file.getvalue()
... st.write(bytes_data)
The above code will give you a BytesIO object, which can then be converted into an array representing the image.
I am working on medical image classification using Resnet50 model. Whenever I try to flatten the layer I am getting this error.
ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.
My code is as below
from PIL import Image
import numpy as np
import tensorflow
from tensorflow.keras import layers
from tensorflow.keras.callbacks import Callback, ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import cohen_kappa_score, accuracy_score
import scipy
from tensorflow.keras import backend as K
import gc
from functools import partial
from tqdm import tqdm
from sklearn import metrics
from collections import Counter
import json
import itertools
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D,GlobalAveragePooling2D
from keras.layers import Input, Lambda, Dense, Flatten
from keras.preprocessing import image
from glob import glob
pre_trained_model = tensorflow.keras.applications.ResNet50(input_shape=(224,224,3), include_top=False, weights="imagenet")
from keras.applications.resnet50 import ResNet50
from keras.models import Model
import keras
restnet = ResNet50(include_top=False, weights='imagenet', input_shape=(224,224,3))
output = restnet.layers[-1].output
output = keras.layers.Flatten()(output)
restnet = Model(restnet.input, output=output)
for layer in restnet.layers:
layer.trainable = False
restnet.summary()
I also tried adding the output layer this way:
last_layer = pre_trained_model.get_layer('conv5_block3_out')
print('last layer output shape:', last_layer.output_shape)
last_output = last_layer.output
x = GlobalAveragePooling2D()(last_output)
x = layers.Dropout(0.5)(x)
x = layers.Dense(3, activation='softmax')(x)
But got this error:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
I am unable to understand both errors, checked the soln given here, but that didn't solve my problem.
You are mixing tensorflow and keras libraries. Recommended to use only tensorflow.keras.* instead of keras.*.
Here is the modified code:
from PIL import Image
import numpy as np
import tensorflow
from tensorflow.keras import layers
from tensorflow.keras.callbacks import Callback, ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import cohen_kappa_score, accuracy_score
import scipy
from tensorflow.keras import backend as K
import gc
from functools import partial
from tqdm import tqdm
from sklearn import metrics
from collections import Counter
import json
import itertools
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D,GlobalAveragePooling2D
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.preprocessing import image
from glob import glob
pre_trained_model = tensorflow.keras.applications.ResNet50(input_shape=(224,224,3), include_top=False, weights="imagenet")
from keras.applications.resnet50 import ResNet50
from keras.models import Model
import keras
restnet = ResNet50(include_top=False, weights='imagenet', input_shape=(224,224,3))
output = restnet.layers[-1].output
output = tensorflow.keras.layers.Flatten()(output)
restnet = tensorflow.keras.models.Model(restnet.input, outputs=output)
for layer in restnet.layers:
layer.trainable = False
restnet.summary()
I am working on a project that detects handwritten characters. There are many packages I have imported. One of the package keras.models.load_model(mnist.h5) is throwing following error:
OSError: Unable to open file (unable to open file: name = 'mnist.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
Code Snippet is:
from keras.models import load_model
from tkinter import *
import tkinter as tk
import win32gui
from PIL import ImageGrab, Image
import numpy as np
model = load_model('mnist.h5')
Using Python 3.7
Can anyone please help me.
Thank you
Please refer working code to import the Mnist data set.
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
#### Import the Fashion MNIST dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()