1

脳腫瘍の MRI 画像を正常、悪性、良性に分類しようとしています。このために、1 つのプログラムで 2 つのニューラル ネットワークを実行したいと考えています。最初のネットワークは、脳の MRI 画像が腫瘍性か非腫瘍性かを分類します。腫瘍の場合、2 番目のネットワークは脳の MRI 画像が悪性か良性かを分類します。コードは次のとおりです。

# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import sys
from PIL import Image
sys.modules['Image'] = Image 
#import PIL as pillow
#from PIL import Image
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (100, 100, 3), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('C:\\Users\\Admin\\Desktop\\tumor_non_tumour\\training',
target_size = (100, 100),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('C:\\Users\\Admin\\Desktop\\tumor_non_tumour\\testing',
target_size = (100, 100),
batch_size = 32,
class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 10,
epochs = 20,
validation_data = test_set,
validation_steps = 10)
# Part 3 - Making new predictions
import numpy as np
from tkinter import *
from tkinter import filedialog
root  = Tk()
from keras.preprocessing import image
test_image = image.load_img(filedialog.askopenfilename( filetypes = ( ("image files" , "*.jpg") , ("all files", "*.*"))), target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 0:
    prediction = 'normal'    
else :
    prediction = 'tumorous'

#print(prediction)

if(result[0][0] == 1) :
    sys.modules['Image'] = Image 
    #import PIL as pillow
    #from PIL import Image
    # Initialising the CNN
    classifier = Sequential()
    # Step 1 - Convolution
    classifier.add(Conv2D(32, (3, 3), input_shape = (100, 100, 3), activation = 'relu'))
    # Step 2 - Pooling
    classifier.add(MaxPooling2D(pool_size = (2, 2)))
    # Adding a second convolutional layer
    classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
    classifier.add(MaxPooling2D(pool_size = (2, 2)))
    # Step 3 - Flattening
    classifier.add(Flatten())
    # Step 4 - Full connection
    classifier.add(Dense(units = 128, activation = 'relu'))
    classifier.add(Dense(units = 1, activation = 'sigmoid'))
    # Compiling the CNN
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    # Part 2 - Fitting the CNN to the images
    #from keras.preprocessing.image import ImageDataGenerator
    train_datagen = ImageDataGenerator(rescale = 1./255,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True)
    test_datagen = ImageDataGenerator(rescale = 1./255)
    training_set = train_datagen.flow_from_directory("C:/Users/Admin/Desktop/malig_benign/training",
    target_size = (100, 100),
    batch_size = 32,
    class_mode = 'binary')
    test_set = test_datagen.flow_from_directory('C:/Users/Admin/Desktop/malig_benign/testing',
    target_size = (100, 100),
    batch_size = 32,
    class_mode = 'binary')
    classifier.fit_generator(training_set,
    steps_per_epoch = 10,
    epochs = 10,
    validation_data = test_set,
    validation_steps = 10)
    # Part 3 - Making new predictions
    #import numpy as np
    #from tkinter import *
    #from tkinter import filedialog

    #from keras.preprocessing import image
    test_image = image.load_img(test_image, target_size = (100, 100))
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    result = classifier.predict(test_image)
    training_set.class_indices
    if result[0][0] == 0:
        prediction = 'malignant'    
    else :
        prediction = 'benign'

    print (prediction)

2 番目のニューラル ネットワークで変数の名前を変更しようとしましたが、それでも最終的な出力は得られませんでした。私はこのエラーが発生しています:

AttributeError                            Traceback (most recent call last)
~\Anaconda3\envs\tensorflow\lib\site-packages\PIL\Image.py in open(fp, mode)
   2546     try:
-> 2547         fp.seek(0)
   2548     except (AttributeError, io.UnsupportedOperation):

AttributeError: 'numpy.ndarray' object has no attribute 'seek'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-2-d9dc0d704b3a> in <module>()
    110 
    111     from keras.preprocessing import image
--> 112     test_image = image.load_img(test_image, target_size = (100, 100))
    113     test_image = image.img_to_array(test_image)
    114     test_image1= np.expand_dims(test_image, axis = 0)

~\Anaconda3\envs\tensorflow\lib\site-packages\keras\preprocessing\image.py in load_img(path, grayscale, target_size, interpolation)
    360         raise ImportError('Could not import PIL.Image. '
    361                           'The use of `array_to_img` requires PIL.')
--> 362     img = pil_image.open(path)
    363     if grayscale:
    364         if img.mode != 'L':

~\Anaconda3\envs\tensorflow\lib\site-packages\PIL\Image.py in open(fp, mode)
   2547         fp.seek(0)
   2548     except (AttributeError, io.UnsupportedOperation):
-> 2549         fp = io.BytesIO(fp.read())
   2550         exclusive_fp = True
   2551 

AttributeError: 'numpy.ndarray' object has no attribute 'read'

誰でも解決方法、または同じことを実装するための他のより良い方法について教えてください。

4

0 に答える 0