Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- app.py +56 -0
- leaf-cnn.ipynb +1 -0
- leaf.jpg +0 -0
- leafmodel.h5 +3 -0
- requirements.txt +2 -0
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
from tensorflow.keras.models import load_model
|
5 |
+
|
6 |
+
# Üzüm yaprağı çeşitleri
|
7 |
+
leaf_varieties = ['ESCA', 'Healthy', 'Leaf Blight', 'Black Rot']
|
8 |
+
|
9 |
+
# Modeli yükleme
|
10 |
+
model = load_model('leafmodel.h5')
|
11 |
+
model.summary()
|
12 |
+
|
13 |
+
def process_img(img):
|
14 |
+
img = img.resize((128, 128), Image.LANCZOS) # 128x128 piksel boyutuna dönüştürme
|
15 |
+
img = np.array(img) / 255.0 # Normalize etme
|
16 |
+
img = np.expand_dims(img, axis=0) # Resme boyut ekleme
|
17 |
+
return img
|
18 |
+
|
19 |
+
st.title("Üzüm Yaprağı Çeşidi Sınıflandırması :leaves:")
|
20 |
+
st.write(
|
21 |
+
"Bir üzüm yaprağı resmi seçin ve modelimiz, bu resmin hangi üzüm yaprağı çeşidinden olduğunu tahmin etsin. 🖼️📊\n"
|
22 |
+
"Upload an image and the model will predict which grape leaf variety your image shows."
|
23 |
+
)
|
24 |
+
|
25 |
+
# Stil ayarları
|
26 |
+
st.markdown("""
|
27 |
+
<style>
|
28 |
+
.reportview-container {
|
29 |
+
background: #F0F2F6;
|
30 |
+
}
|
31 |
+
.sidebar .sidebar-content {
|
32 |
+
background: #E0E0E0;
|
33 |
+
}
|
34 |
+
.css-18e3th9 {
|
35 |
+
font-size: 1.25em;
|
36 |
+
color: #333;
|
37 |
+
}
|
38 |
+
</style>
|
39 |
+
""", unsafe_allow_html=True)
|
40 |
+
|
41 |
+
file = st.file_uploader("Resim Yükle & Bir resim seçiniz", type=['png', 'jpg', 'jpeg'])
|
42 |
+
|
43 |
+
if file is not None:
|
44 |
+
img = Image.open(file)
|
45 |
+
st.image(img, caption="Yüklenen Resim", use_column_width=True)
|
46 |
+
|
47 |
+
result = process_img(img)
|
48 |
+
prediction = model.predict(result)
|
49 |
+
prediction_class = np.argmax(prediction) # En yüksek tahmin edilen sınıf
|
50 |
+
|
51 |
+
# Sınıf isimleri
|
52 |
+
result_text = leaf_varieties[prediction_class]
|
53 |
+
|
54 |
+
st.write(f"**Sonuç:** {result_text}")
|
55 |
+
else:
|
56 |
+
st.write("Lütfen bir resim yükleyin.")
|
leaf-cnn.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":4948090,"sourceType":"datasetVersion","datasetId":2869270}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n #print(os.path.join(dirname, filename))\n pass","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Bu projede Yaprakların Sağlıklı olup olmadığına göre 4 çeşit guruptan hangilerine girdiklerini kontrol ediceğiz modellimiz için de CNN kullanıcağız ","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore') \n\nimport cv2\nimport os\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom sklearn.model_selection import train_test_split\n\npath='/kaggle/input/augmented-grape-disease-detection-dataset/Final Training Data/'","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_dataset(folders, path, max_images_per_label=1000):\n data = {'imgpath': [], 'labels': []}\n \n for folder in folders:\n folderpath = os.path.join(path, folder)\n files = os.listdir(folderpath)\n \n # Her bir klasörden sadece max_images_per_label kadar görsel alıyoruz\n selected_files = files[:max_images_per_label]\n \n for file in selected_files:\n filepath = os.path.join(folderpath, file)\n data['imgpath'].append(filepath)\n data['labels'].append(folder)\n\n dataset = pd.DataFrame(data)\n return dataset","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os \n\nsınıf=os.listdir(path) # Kolon adlarımız \nnum_classes = len(os.listdir(path))\nprint('Sınıflarımız: ',sınıf,'\\nSınıf sayisi:',num_classes)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"folders1 = ['ESCA', 'Healthy', 'Leaf Blight', 'Black Rot']\ndf=create_dataset(folders1,path)\ndf.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\nfor index, row in df.sample(7).iterrows():\n # Resmi yükle\n img = cv2.imread(row['imgpath'])\n \n # OpenCV resmi RGB formatına dönüştür\n img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n \n # Resmi matplotlib ile göster\n plt.figure(figsize=(6, 6))\n plt.imshow(img_rgb)\n plt.title(row['labels'])\n plt.axis('off')\n plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\nimport matplotlib.pyplot as plt\nimport plotly.express as px\n\nsayi = df['labels'].value_counts() #hurma türe göre sayisi \n \n# Plotly ile hurma dağılımını görselleştirme\nfig=px.bar(x=sayi.index, #6 indexi var\n y=sayi.values, # sayisi \n color=sayi.index, # rekleri yine sayisina göre\n labels={'x': 'Çeşitler','y': 'Toplam Sayı'}, #label yazdırma\n title='Yaprak Çeşitleri Grafiği', #başlık \n template='plotly_dark') # arkapılan \n\nfig.show()\n\n\nfig = px.pie(names=sayi.index,\n values=sayi.values,\n title='Yaprak Dağılımı',\n labels={'names': 'Hurma',\n 'values': 'Toplam Sayı'},\n template='plotly_white')\nfig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# Normalizasyon","metadata":{}},{"cell_type":"code","source":"df = df.sample(frac=1).reset_index(drop=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nx=[]\nfor img in df['imgpath']:\n try:\n img = cv2.imread(img)\n img = cv2.resize(img, (128, 128))# 128 pixle boyutunda\n img = img / 255.0 # normalize etmee \n x.append(img) # img \n\n except:\n print(f\"Error loading image: {img}\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modelin","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nencoder = LabelEncoder()\n\n# Etiketleri sayısal değerlere dönüştür\ndf['encode_label'] = encoder.fit_transform(df['labels'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x=np.array(x)\ny=df['encode_label']\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)\n\nx_train.shape,x_test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = models.Sequential()\n\n# Evrişimsel katmanlar(Conv) ve havuzlama(pooling) katmanları\n\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Dropout(0.25)) # overfiting yapasın diye bazı değerleri atıyoruz dropout ile\n\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(256, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Dropout(0.25))\n\n# Düzleştirme ve tam bağlı katmanlar\nmodel.add(layers.Flatten()) # düzleştirme\n\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dropout(0.5)) # Yüksek dropout oranı, tam bağlı katmanlarda aşırı öğrenmeyi azaltabilir\nmodel.add(layers.Dense(4, activation='softmax')) # Çıkış katmanı: 4 sınıf için # çeşit sayımıza göre \n\n# Modeli derleme\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\n\nhistory = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=30, batch_size=150)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Sonçlar çok iyi \nmodel.save('model_leaf_99.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Eğitim ve Doğrulama Kaybı\nplt.plot(history.history['loss'], label='Eğitim Kaybı')\nplt.plot(history.history['val_loss'], label='Doğrulama Kaybı')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n\n# Eğitim ve Doğrulama Doğruluğu\nplt.plot(history.history['accuracy'], label='Eğitim Doğruluğu')\nplt.plot(history.history['val_accuracy'], label='Doğrulama Doğruluğu')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss,acc=model.evaluate(x_test,y_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict=model.predict(x_test)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\n\n\nsns.heatmap(confusion_matrix(y_test, np.argmax(predict, axis=1)), annot=True, fmt='d', annot_kws={\"size\": 16})\nplt.title('Confusion Matrix', fontsize=18)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-08-01T03:13:48.232448Z","iopub.execute_input":"2024-08-01T03:13:48.232871Z","iopub.status.idle":"2024-08-01T03:13:49.193164Z","shell.execute_reply.started":"2024-08-01T03:13:48.232837Z","shell.execute_reply":"2024-08-01T03:13:49.192226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Burada 1000 tane gözükemsinin nedeni bizim test değerlerimizin adedi oluyor 4000 göresl üzernde işlem yaptık 1000 tansei test ,3000 train","metadata":{}},{"cell_type":"code","source":"print(classification_report(y_test,np.argmax(predict,axis=1)))\n","metadata":{"execution":{"iopub.status.busy":"2024-08-01T03:16:42.630065Z","iopub.execute_input":"2024-08-01T03:16:42.630806Z","iopub.status.idle":"2024-08-01T03:16:42.646545Z","shell.execute_reply.started":"2024-08-01T03:16:42.630772Z","shell.execute_reply":"2024-08-01T03:16:42.645603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Sonuç olarak CNN ile İyi bir model Skoruna gelebildik , biz bu modeli applerimizde kullanmak için save edeceğiz","metadata":{}},{"cell_type":"code","source":"model.save('model_leaf.h6')","metadata":{},"execution_count":null,"outputs":[]}]}
|
leaf.jpg
ADDED
![]() |
leafmodel.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fca71a4ac6ed1eaf82453b2bfca74047db470635b2a9f0eab55948b766787d06
|
3 |
+
size 12829312
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
tensorflow
|
2 |
+
streamlit
|