Пример #1
0
 def test_smart_resize_errors(self):
     with self.assertRaisesRegex(ValueError, 'a tuple of 2 integers'):
         preprocessing_image.smart_resize(np.random.random((20, 20, 2)),
                                          size=(10, 5, 3))
     with self.assertRaisesRegex(ValueError, 'incorrect rank'):
         preprocessing_image.smart_resize(np.random.random((20, 40)),
                                          size=(10, 5))
Пример #2
0
 def test_smart_resize(self):
     test_input = np.random.random((20, 40, 3))
     output = preprocessing_image.smart_resize(test_input, size=(50, 50))
     self.assertIsInstance(output, np.ndarray)
     self.assertListEqual(list(output.shape), [50, 50, 3])
     output = preprocessing_image.smart_resize(test_input, size=(10, 10))
     self.assertListEqual(list(output.shape), [10, 10, 3])
     output = preprocessing_image.smart_resize(test_input, size=(100, 50))
     self.assertListEqual(list(output.shape), [100, 50, 3])
     output = preprocessing_image.smart_resize(test_input, size=(5, 15))
     self.assertListEqual(list(output.shape), [5, 15, 3])
Пример #3
0
    def predict(self, uploaded_image: TemporaryUploadedFile) -> (List, Image):
        """
        Read image and predict category
        """
        # convert the image pixels to a numpy array
        image = img_to_array(Image.open(uploaded_image))

        # resize (crop) to vgg16 size (331, 331, 3)
        image = smart_resize(image, (331, 331))

        # grab a RGB preview for frontend
        rgb_preview = Image.fromarray(np.uint8(image)).convert('RGB')

        # reshape data for the model, add new axis (1, 224, 224, 3)
        image = np.expand_dims(image, axis=0)

        # prepare the image for the VGG model (subtracts the mean RGB channels)
        image = preprocess_input(image)

        # predict the probability across all output classes
        what = self.model.predict(image)

        # convert the probabilities to class labels
        labels = decode_predictions(what, top=3)

        # make it readable
        labels = self.labels_to_percents(labels)

        return labels, rgb_preview
Пример #4
0
    def processing_pipeline(self, scan_dir):
        """Extract slices through the temporal lobe from each scan

        Args:
            scan_dir (str): Path to scans

        Returns:
            ndarray: Output tensor of size (number scans, y size, x size, 1)
            list: List of scan filenames
        """
        images = []
        scan_filenames = list(scan_dir.glob("*.nii.gz"))
        out_filenames = []
        for scan_filename in scan_filenames:
            scan = nib.load(scan_filename).get_fdata()

            scan_new = self.crop_scan(scan)
            for im in self.slice_temporal_lobe(scan_new):
                im_new = self.normalize_image(im)
                im_new = im_new[:, :, np.newaxis]
                im_new = smart_resize(im_new, size=self.desired_image_size)
                images.append(im_new[np.newaxis])
                out_filenames.append(scan_filename)

        images = np.vstack(images)
        return images, out_filenames
Пример #5
0
    def test_smart_resize_tf_dataset(self, size):
        test_input_np = np.random.random((2, 20, 40, 3))
        test_ds = Dataset.from_tensor_slices(test_input_np)

        resize = lambda img: preprocessing_image.smart_resize(img, size=size)
        test_ds = test_ds.map(resize)
        for sample in test_ds.as_numpy_iterator():
            self.assertIsInstance(sample, np.ndarray)
            self.assertListEqual(list(sample.shape), [size[0], size[1], 3])
Пример #6
0
def keras_predict(model, img):
    img = image.smart_resize(img, size=(200, 200))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    images = np.vstack([x])
    classes = model.predict(images)
    max_id, max_prob = -1, -1
    for i in range(len(classes[0])):
        if classes[0][i] > max_prob:
            max_id = i
            max_prob = classes[0][i]
    return max_prob, max_id
Пример #7
0
def load_image(path, image_size, num_channels, interpolation,
               crop_to_aspect_ratio=False):
  """Load an image from a path and resize it."""
  img = tf.io.read_file(path)
  img = tf.image.decode_image(
      img, channels=num_channels, expand_animations=False)
  if crop_to_aspect_ratio:
    img = keras_image_ops.smart_resize(img, image_size,
                                       interpolation=interpolation)
  else:
    img = tf.image.resize(img, image_size, method=interpolation)
  img.set_shape((image_size[0], image_size[1], num_channels))
  return img
Пример #8
0
async def dlmodel(request: Request):
    #Get response
    req = await request.json()
    #Get values of the response and turn it into a numpy array
    digit = np.array(list(req['digit'].values()))
    #Reshape 
    digit = digit.reshape(round(sqrt(len(digit))), round(sqrt(len(digit))) ,1)
    #Resize
    digit = smart_resize(digit,size=(28,28))
    #Predict
    answer = dl.predict(digit.reshape(1,28,28,1))

    print(answer.round(3))
    return answer.tolist()
Пример #9
0
async def test(request: Request):
    req = await request.json()
    digit = np.array(list(req['digit'].values()))
    digit = digit.reshape(400,400,1)
    digit = smart_resize(digit,size=(28,28))

    # plt.figure()
    # plt.imshow(digit)
    # plt.show()

    answer = dl.predict(digit.reshape(1,28,28,1))

    print(answer)
    return answer.round(2).tolist()
    
Пример #10
0
    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples'  # X : (n_samples, *image_size, n_channels)
        X = np.empty((self.batch_size, *self.image_size, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        for i, ID in enumerate(list_IDs_temp):

            Xi = load_img(os.path.join(self.data_path, ID))
            Xi = smart_resize(np.asarray(Xi), self.image_size)
            X[i, :] = Xi

            y[i] = self.classes.index(ID.split('/')[0])
        if self.transform:
            data_augmentation = tf.keras.Sequential([
                tf.keras.layers.experimental.preprocessing.RandomFlip(
                    "horizontal_and_vertical"),
                tf.keras.layers.experimental.preprocessing.RandomRotation(0.2)
            ])
            X = data_augmentation(X)

        return X, keras.utils.to_categorical(y, num_classes=6)
Пример #11
0
import keras
from keras.preprocessing import image
import dlib
import matplotlib.pyplot as plt
import cv2
from PIL import Image
detector = dlib.get_frontal_face_detector()
img = image.load_img('D:/Data science/dlib starting/chachi.jpg')
img = image.img_to_array(img)
img = img.astype('uint8')
faces = detector(img)
model = keras.models.load_model('D:/Data science/dlib starting/new_model.h5')
for face in faces:
    x1, y1 = face.left(), face.top()
    x2, y2 = face.right(), face.bottom()
    new_img = img[y1 - 30:y2 + 10, x1 - 30:x2 + 10]
    new_img1 = image.smart_resize(new_img, (150, 150)) / 255
    # plt.imshow(new_img/255)
    # plt.show()
    # plt.imshow(new_img1/255)
    # plt.show()
    # print(new_img.shape)
    # print(new_img1.shape)
    print(new_img1.shape)
    print(model.predict_classes(new_img1.reshape(1, 150, 150, 3))[0])