我正在尝试将脑肿瘤的MRI图像分类为正常,恶性或良性。为此,我想在一个程序中运行两个神经网络。第一个网络分类脑MRI是否是肿瘤或非肿瘤。如果肿瘤,第二个网络分类脑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)
我甚至尝试在第二个神经网络中更改变量的名称,但仍未获得最终输出。我收到了这个错误:
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'
任何人都可以请教我如何解决,或者哪种方法更好地实现。