text_plain_output_1.png
from PIL import Image

from keras.layers import Conv2D, MaxPooling2D

from keras.layers import Dense, Dropout, Flatten

from keras.models import Sequential

from keras.preprocessing import image

from lime import lime_image

from skimage.segmentation import mark_boundaries

from sklearn.model_selection import train_test_split

from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import numpy as np

import numpy as np # linear algebra

import os

import xml.etree.ElementTree as ET

from PIL import Image
def change_image_channels(image, image_path):
    if image.mode == 'RGBA':
        r, g, b, a = image.split()
        image = Image.merge('RGB', (r, g, b))
        image.save(image_path)
    elif image.mode != 'RGB':
        image = image.convert('RGB')
        os.remove(image_path)
        image.save(image_path)
    return image
for i in range(212):
    if i >= 189 and i <= 195 or (i >= 203 and i <= 207):
        continue
    im = Image.open('/kaggle/input/fruit-detection/images/fruit{}.png'.format(i))
    change_image_channels(im, 'fruit_change{}.png'.format(i))

import matplotlib.pyplot as plt
ims = np.zeros((200, 300, 400, 3))
q = 0
for i in range(212):
    if i >= 189 and i <= 195 or (i >= 203 and i <= 207):
        continue
    try:
        im = plt.imread('fruit_change{}.png'.format(i))
        ims[q, :, :, :] = im
        q = q + 1
    except:
        try:
            im = Image.open('fruit_change{}.png'.format(i))
        except:
            im = Image.open('/kaggle/input/fruit-detection/images/fruit{}.png'.format(i))
        imBackground = im.resize((400, 300))
        imBackground.save('ProcessedImage{}.png'.format(i), 'png')
        im = plt.imread('ProcessedImage{}.png'.format(i))
        size = im.shape
        x = size[0]
        y = size[1]
        channels = size[2]
        ims[q, 0:x, 0:y, 0:channels] = im
        q = q + 1

import xml.etree.ElementTree as ET
output = np.zeros((200, 4))
q = 0
for i in range(212):
    if i >= 189 and i <= 195 or (i >= 203 and i <= 207):
        continue
    tree = ET.parse('/kaggle/input/fruit-detection/annotations/fruit{}.xml'.format(i))
    root = tree.getroot()
    for elem in root:
        for subelem in elem:
            if subelem.tag == 'name':
                if subelem.text == 'snake fruit':
                    output[q, 0] = 1
                elif subelem.text == 'dragon fruit':
                    output[q, 1] = 1
                elif subelem.text == 'banana':
                    output[q, 2] = 1
                elif subelem.text == 'pineapple':
                    output[q, 3] = 1
    q = q + 1

from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(ims, output, test_size=0.3, random_state=0)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

model = Sequential()
model.add(Conv2D(filters=16, kernel_size=(5, 5), activation='relu', input_shape=(300, 400, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=32, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=64, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=64, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4, activation='sigmoid'))
model.summary()

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=100, validation_data=(x_test, y_test), batch_size=64)

scores = model.evaluate(x_test, y_test, verbose=0)
predictions = model.predict(x_test[0:4, :, :, :])

from lime import lime_image
from lime.wrappers.scikit_image import SegmentationAlgorithm
from skimage.segmentation import mark_boundaries
image_example = ims[2]
explainer = lime_image.LimeImageExplainer(verbose=False)
explanation = explainer.explain_instance(image_example, classifier_fn=model.predict, top_labels=100, hide_color=0, num_samples=1000)
temp, mask = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=False, num_features=5, hide_rest=False)
plt.imshow(mark_boundaries(temp, mask))