{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"},{"sourceId":13103641,"sourceType":"datasetVersion","datasetId":8300450}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\n\nimport cv2\nimport random\nimport shutil\nimport zipfile\nimport time\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\nimport matplotlib.pyplot as plt\n\nprint(\"\\nProje için tüm kütüphaneler başarıyla import edildi.\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-09-19T01:24:42.260419Z","iopub.execute_input":"2025-09-19T01:24:42.261375Z","iopub.status.idle":"2025-09-19T01:24:42.274352Z","shell.execute_reply.started":"2025-09-19T01:24:42.261346Z","shell.execute_reply":"2025-09-19T01:24:42.273448Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Hasar efekti fonksiyonlarını tanımla\n\ndef apply_wrinkle_effect(image):\n    rows, cols, _ = image.shape\n    x_map, y_map = np.zeros((rows, cols), np.float32), np.zeros((rows, cols), np.float32)\n    frequency, amplitude = np.random.uniform(5, 10), np.random.uniform(10, 20)\n    for i in range(rows):\n        for j in range(cols):\n            x_map[i, j] = j + amplitude * np.cos(2 * np.pi * i / (rows / frequency))\n            y_map[i, j] = i + amplitude * np.sin(2 * np.pi * j / (cols / frequency))\n    return cv2.remap(image, x_map, y_map, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)\n\ndef apply_stain_effect(image):\n    stained_image = image.copy()\n    rows, cols, _ = image.shape\n    center_x, center_y = np.random.randint(0, cols), np.random.randint(0, rows)\n    radius = np.random.randint(int(cols/10), int(cols/4))\n    color, alpha = (33, 67, 101), 0.4 # BGR formatında kahverengi ve şeffaflık\n    overlay = stained_image.copy()\n    cv2.circle(overlay, (center_x, center_y), radius, color, -1)\n    cv2.addWeighted(overlay, alpha, stained_image, 1 - alpha, 0, stained_image)\n    return stained_image\n\ndef apply_tear_effect(image):\n    torn_image = image.copy()\n    rows, cols, _ = image.shape\n    tear_x, tear_y = np.random.randint(int(cols/4), int(cols/2)), np.random.randint(int(rows/4), int(rows/2))\n    corner = np.random.randint(0, 4)\n    if corner == 0: pts = np.array([[0, 0], [tear_x, 0], [0, tear_y]], np.int32)\n    elif corner == 1: pts = np.array([[cols, 0], [cols - tear_x, 0], [cols, tear_y]], np.int32)\n    elif corner == 2: pts = np.array([[0, rows], [0, rows - tear_y], [tear_x, rows]], np.int32)\n    else: pts = np.array([[cols, rows], [cols - tear_x, rows], [cols, rows - tear_y]], np.int32)\n    cv2.fillPoly(torn_image, [pts], (0, 0, 0))\n    return torn_image\n\nprint(\"Özel veri artırma fonksiyonları tanımlandı.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-19T01:24:42.275805Z","iopub.execute_input":"2025-09-19T01:24:42.276147Z","iopub.status.idle":"2025-09-19T01:24:42.288304Z","shell.execute_reply.started":"2025-09-19T01:24:42.276126Z","shell.execute_reply":"2025-09-19T01:24:42.287381Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Zip dosyasını aç ve küçük veri setini üret\n\n# Adım 1: Zip Dosyasını Aç\nprint(\"Zip dosyası açılıyor...\")\nzip_path = '/kaggle/input/dogs-vs-cats/train.zip'\nextract_path = '/kaggle/working/'\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\nprint(\"-> Zip dosyası açıldı.\")\n\n# Adım 2: Küçük Veri Setini Üret (Proof-of-Concept)\nprint(\"Küçük veri seti üretiliyor...\")\nstart_time = time.time()\nsource_dir = '/kaggle/working/train/'\nbase_dir = '/kaggle/working/dataset/'\nsaglam_dir = os.path.join(base_dir, 'saglam')\nhasarli_dir = os.path.join(base_dir, 'hasarli')\nos.makedirs(saglam_dir, exist_ok=True)\nos.makedirs(hasarli_dir, exist_ok=True)\nall_images = os.listdir(source_dir)\nrandom.shuffle(all_images)\nnum_samples = 200 # Küçük set ile test\nfor img_name in all_images[:num_samples]: shutil.copyfile(os.path.join(source_dir, img_name), os.path.join(saglam_dir, img_name))\nefektler = [apply_wrinkle_effect, apply_stain_effect, apply_tear_effect]\nfor img_name in all_images[num_samples:num_samples*2]:\n    original_image = cv2.imread(os.path.join(source_dir, img_name))\n    if original_image is not None:\n        secilen_efekt = random.choice(efektler)\n        hasarli_image = secilen_efekt(original_image)\n        cv2.imwrite(os.path.join(hasarli_dir, 'hasarli_' + img_name), hasarli_image)\nend_time = time.time()\nprint(f\"-> Veri seti üretimi tamamlandı! Süre: {end_time - start_time:.2f} saniye.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-19T01:24:42.289258Z","iopub.execute_input":"2025-09-19T01:24:42.289567Z","iopub.status.idle":"2025-09-19T01:25:19.280442Z","shell.execute_reply.started":"2025-09-19T01:24:42.289541Z","shell.execute_reply":"2025-09-19T01:25:19.279693Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Veriyi Hazırla, Modeli Kur, Eğit ve Sonuçları Göster\n\n# Adım 1: Veriyi Modele Hazırla\nprint(\"Veri, model için hazırlanıyor...\")\nIMG_WIDTH, IMG_HEIGHT, BATCH_SIZE = 150, 150, 32\nbase_dir = '/kaggle/working/dataset/'\nimage_generator = ImageDataGenerator(rescale=1./255, validation_split=0.2)\ntrain_generator = image_generator.flow_from_directory(directory=base_dir, target_size=(IMG_WIDTH, IMG_HEIGHT), batch_size=BATCH_SIZE, class_mode='binary', subset='training')\nvalidation_generator = image_generator.flow_from_directory(directory=base_dir, target_size=(IMG_WIDTH, IMG_HEIGHT), batch_size=BATCH_SIZE, class_mode='binary', subset='validation')\nprint(\"-> Veri jeneratörleri hazır.\")\n\n# Adım 2: Modeli Oluştur ve Eğit\nprint(\"\\nModel mimarisi kuruluyor ve eğitim başlatılıyor...\")\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_WIDTH, IMG_HEIGHT, 3)), MaxPooling2D(2, 2),\n    Conv2D(64, (3, 3), activation='relu'), MaxPooling2D(2, 2),\n    Conv2D(128, (3, 3), activation='relu'), MaxPooling2D(2, 2),\n    Flatten(), Dropout(0.5),\n    Dense(512, activation='relu'),\n    Dense(1, activation='sigmoid')\n])\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\nepochs = 15\nhistory = model.fit(train_generator, epochs=epochs, validation_data=validation_generator)\nprint(\"\\n--- EĞİTİM BAŞARIYLA TAMAMLANDI! ---\")\n\n# Adım 3: Eğitim Sonuçlarını Görselleştir\nprint(\"\\nEğitim performans grafikleri çiziliyor...\")\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs_range = range(epochs)\nplt.figure(figsize=(14, 7))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Eğitim Başarımı')\nplt.plot(epochs_range, val_acc, label='Doğrulama Başarımı')\nplt.legend(loc='lower right')\nplt.title('Eğitim ve Doğrulama Başarımı')\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Eğitim Kaybı')\nplt.plot(epochs_range, val_loss, label='Doğrulama Kaybı')\nplt.legend(loc='upper right')\nplt.title('Eğitim ve Doğrulama Kaybı')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-19T01:25:19.282350Z","iopub.execute_input":"2025-09-19T01:25:19.282580Z","iopub.status.idle":"2025-09-19T01:25:49.012570Z","shell.execute_reply.started":"2025-09-19T01:25:19.282563Z","shell.execute_reply":"2025-09-19T01:25:49.011751Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nimport numpy as np\n\n# Test için 'hasarli' veya 'saglam' klasörünü seçebilirsin\ntest_klasoru = hasarli_dir \nrastgele_resim = random.choice(os.listdir(test_klasoru))\nresim_yolu = os.path.join(test_klasoru, rastgele_resim)\n\nprint(f\"Test için seçilen resim: {resim_yolu}\")\n\n# Resmi modele uygun boyuta getir ve yükle\nimg = image.load_img(resim_yolu, target_size=(IMG_WIDTH, IMG_HEIGHT))\n\n# Resmi bir sayı dizisine çevir\nimg_array = image.img_to_array(img)\n# Piksel değerlerini 0-1 arasına ölçeklendir\nimg_array /= 255.0\n# Modele tek bir resim göndereceğimizi belirtmek için boyut ekle\nimg_array = np.expand_dims(img_array, axis=0)\n\n# TAHMİN YAP\ntahmin = model.predict(img_array)\n\nif tahmin[0][0] < 0.5:\n    sonuc = f\"Tahmin: HASARLI (Skor: {tahmin[0][0]:.2f})\"\nelse:\n    sonuc = f\"Tahmin: SAĞLAM (Skor: {tahmin[0][0]:.2f})\"\n\nprint(sonuc)\n\n# Sonucu görselleştir\nplt.figure(figsize=(6, 6))\nplt.imshow(img)\nplt.title(sonuc)\nplt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-19T01:25:49.013130Z","iopub.execute_input":"2025-09-19T01:25:49.013353Z","iopub.status.idle":"2025-09-19T01:25:49.452793Z","shell.execute_reply.started":"2025-09-19T01:25:49.013336Z","shell.execute_reply":"2025-09-19T01:25:49.452121Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nresim_yolu = '/kaggle/input/test-resmim/indir (1).png' \n\nprint(f\"Test için seçilen resim: {resim_yolu}\")\n\n\n\nimg = image.load_img(resim_yolu, target_size=(IMG_WIDTH, IMG_HEIGHT))\nimg_array = image.img_to_array(img)\nimg_array /= 255.0\nimg_array = np.expand_dims(img_array, axis=0)\n\ntahmin = model.predict(img_array)\n\nif tahmin[0][0] < 0.5:\n    sonuc = f\"Tahmin: HASARLI (Skor: {tahmin[0][0]:.2f})\"\nelse:\n    sonuc = f\"Tahmin: SAĞLAM (Skor: {tahmin[0][0]:.2f})\"\n\nprint(sonuc)\n\nplt.figure(figsize=(6, 6))\nplt.imshow(img)\nplt.title(sonuc)\nplt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-19T01:25:49.453731Z","iopub.execute_input":"2025-09-19T01:25:49.454356Z","iopub.status.idle":"2025-09-19T01:25:49.639293Z","shell.execute_reply.started":"2025-09-19T01:25:49.454328Z","shell.execute_reply":"2025-09-19T01:25:49.638555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}