Ejemplo n.º 1
0
    def read_file(self, filename):
        im = Image.open(filename)
        r, g, b = im.split()
        r_arr = plimg.pil_to_array(r)
        g_arr = plimg.pil_to_array(g)
        b_arr = plimg.pil_to_array(b)

        r_arr1 = r_arr.reshape(1024)
        g_arr1 = g_arr.reshape(1024)
        b_arr1 = b_arr.reshape(1024)

        arr = np.concatenate((r_arr1, g_arr1, b_arr1))
        return arr
Ejemplo n.º 2
0
    def readFile(self, filename, file):
        im = Image.open(filename)

        r, g, b = im.split()

        r_arr = plimg.pil_to_array(r)
        g_arr = plimg.pil_to_array(g)
        b_arr = plimg.pil_to_array(b)

        arr = np.concatenate((r_arr, g_arr, b_arr))
        label = []
        for i in file:
            label.append(i[0])
        return arr,label
Ejemplo n.º 3
0
 def read_file(filename):
     im = Image.open(filename)  # 打开一个图像
     # 将图像的RGB分离
     r, g, b = im.split()
     # 将PILLOW图像转成数组
     r_arr = plimg.pil_to_array(r)
     g_arr = plimg.pil_to_array(g)
     b_arr = plimg.pil_to_array(b)
     # 将32*32二位数组转成1024的一维数组
     r_arr1 = r_arr.reshape(1024)
     g_arr1 = g_arr.reshape(1024)
     b_arr1 = b_arr.reshape(1024)
     # 3个一维数组合并成一个一维数组,大小为3072
     arr = np.concatenate((r_arr1, g_arr1, b_arr1))
     return arr
Ejemplo n.º 4
0
def create_heatmap(xs, ys, imageSize, blobSize, cmap):
    blob = Image.new('RGBA', (blobSize * 2, blobSize * 2), '#000000')
    blob.putalpha(0)
    colour = 255 / int(math.sqrt(len(xs)))
    draw = ImageDraw.Draw(blob)
    draw.ellipse((blobSize / 2, blobSize / 2, blobSize * 1.5, blobSize * 1.5),
                 fill=(colour, colour, colour))
    blob = blob.filter(ImageFilter.GaussianBlur(radius=blobSize / 2))
    heat = Image.new('RGBA', (imageSize, imageSize), '#000000')
    heat.putalpha(0)
    xScale = float(imageSize - 1) / (max(xs) - min(xs))
    yScale = float(imageSize - 1) / (min(ys) - max(ys))
    xOff = min(xs)
    yOff = max(ys)
    for i in range(len(xs)):
        xPos = int((xs[i] - xOff) * xScale)
        yPos = int((ys[i] - yOff) * yScale)
        blobLoc = Image.new('RGBA', (imageSize, imageSize), '#000000')
        blobLoc.putalpha(0)
        blobLoc.paste(blob, (xPos - blobSize, yPos - blobSize), blob)
        heat = ImageChops.add(heat, blobLoc)

    norm = Normalize(vmin=min(min(heat.getdata())),
                     vmax=max(max(heat.getdata())))
    sm = ScalarMappable(norm, cmap)
    heatArray = pil_to_array(heat)
    rgba = sm.to_rgba(heatArray[:, :, 0], bytes=True)
    rgba[:, :, 3] = heatArray[:, :, 3]
    coloured = Image.fromarray(rgba, 'RGBA')

    return coloured
Ejemplo n.º 5
0
def _matplotlib_pil_bug_present():
    """
    Determine whether PIL images should be pre-flipped due to a bug in Matplotlib.

    Prior to Matplotlib 1.2.0, RGB images provided as PIL objects were
    oriented wrongly. This function tests whether the bug is present.
    """

    from matplotlib.image import pil_to_array

    try:
        from PIL import Image
    except:
        import Image

    from astropy import log

    array1 = np.array([[1, 2], [3, 4]], dtype=np.uint8)
    image = Image.fromarray(array1)
    array2 = pil_to_array(image)

    if np.all(array1 == array2):
        log.debug("PIL Image flipping bug not present in Matplotlib")
        return False
    elif np.all(array1 == array2[::-1, :]):
        log.debug("PIL Image flipping bug detected in Matplotlib")
        return True
    else:
        log.warning(
            "Could not properly determine Matplotlib behavior for RGB images - image may be flipped incorrectly"
        )
        return False
Ejemplo n.º 6
0
    def _gaussFilter(self):
        kernelSize = 7
        imgMatrix = self.selectedItem.image
        size = imgMatrix.shape
        gaussianMatrix = MImage.pil_to_array(Image.new('L', imgMatrix.shape,
                                                       0))
        matrix = gkern(kernelSize)
        for i in range(size[1] - (kernelSize - 1)):
            for j in range(size[0] - (kernelSize - 1)):
                iS = i + (kernelSize - 1) / 2
                jS = j + (kernelSize - 1) / 2
                #print t[i:(i + kernelSize), j:(j + kernelSize)]
                gaussianMatrix[iS, jS] = np.sum(
                    np.multiply(
                        imgMatrix[i:(i + kernelSize), j:(j + kernelSize)],
                        matrix))
                #s[iS, jS] = np.sum(t[i:(i + kernelSize), j:(j + kernelSize)],)/kernelSize**2

        item = QtGui.QStandardItem("new")
        item.imageFileName = None

        item.image = gaussianMatrix
        Image.fromarray(gaussianMatrix).save("bliblop", "BMP")
        item.pixmap = QtGui.QPixmap("bliblop")

        self.model.appendRow(item)
        self.ui.imageListView.setModel(self.model)
Ejemplo n.º 7
0
def test_load_normalization():
    """Test that we're normalizing imported images correctly."""
    # High res map
    map = starry.Map(30)

    # Render the image with starry
    map.load("jupiter")
    img1 = map.render(projection="rect", res=360)
    img1 = img1.flatten()

    # Get the image directly
    earth = os.path.join(os.path.dirname(starry.__file__), "img",
                         "jupiter.jpg")
    grayscale_pil_image = Image.open(earth).convert("L")
    img2 = pil_to_array(grayscale_pil_image)
    img2 = np.array(img2, dtype=float)
    img2 /= 255.0  # to [0, 1] range
    img2 = np.flipud(img2)  # align
    img2 = img2[::2, ::4]  # downsample
    img2 = img2.flatten()

    # Compute stats
    mu1 = np.mean(img1)
    sig1 = np.std(img1)
    mu2 = np.mean(img2)
    sig2 = np.std(img2)
    print(sig2 - sig1)

    # Assert within a couple percent
    assert np.abs(mu1 - mu2) < 0.01
    assert np.abs(sig1 - sig2) < 0.02
Ejemplo n.º 8
0
    def _openFile(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, "OpenImage", "src",
                                                     "Bitmaps (*.bmp)")

        if fileName == "":
            h.warn("No file selected.")
            return

        h.log("Loaded!")
        #self.pixmapItem = QtGui.QPixmap(fileName)
        #item = QtGui.QGraphicsPixmapItem(self.pixmapItem)
        #self.scene.addItem(item)

        item = QtGui.QStandardItem(os.path.basename(str(fileName)))
        item.imageFileName = str(fileName)
        orgImg = Image.open(str(fileName), mode='r').convert()
        item.image = MImage.pil_to_array(orgImg.convert('L'))
        item.pixmap = QtGui.QPixmap(fileName)

        #item.setCheckable(True)

        self.model.appendRow(item)
        self.ui.imageListView.setModel(self.model)

        self._checkButtons()
Ejemplo n.º 9
0
def create_heatmap(xs, ys, imageSize, blobSize, cmap):
    blob = Image.new('RGBA', (blobSize * 2, blobSize * 2), '#000000')
    blob.putalpha(0)
    colour = 255 / int(math.sqrt(len(xs)))
    draw = ImageDraw.Draw(blob)
    draw.ellipse((blobSize / 2, blobSize / 2, blobSize * 1.5, blobSize * 1.5),
                 fill=(colour, colour, colour))
    blob = blob.filter(ImageFilter.GaussianBlur(radius=blobSize / 2))
    heat = Image.new('RGBA', (imageSize, imageSize), '#000000')
    heat.putalpha(0)
    xScale = float(imageSize - 1) / (max(xs) - min(xs))
    yScale = float(imageSize - 1) / (min(ys) - max(ys))
    xOff = min(xs)
    yOff = max(ys)
    for i in range(len(xs)):
        xPos = int((xs[i] - xOff) * xScale)
        yPos = int((ys[i] - yOff) * yScale)
        blobLoc = Image.new('RGBA', (imageSize, imageSize), '#000000')
        blobLoc.putalpha(0)
        blobLoc.paste(blob, (xPos - blobSize, yPos - blobSize), blob)
        heat = ImageChops.add(heat, blobLoc)

    norm = Normalize(vmin=min(min(heat.getdata())),
                     vmax=max(max(heat.getdata())))
    sm = ScalarMappable(norm, cmap)
    heatArray = pil_to_array(heat)
    rgba = sm.to_rgba(heatArray[:, :, 0], bytes=True)
    rgba[:, :, 3] = heatArray[:, :, 3]
    coloured = Image.fromarray(rgba, 'RGBA')

    return coloured
Ejemplo n.º 10
0
def bg_compensate(img, sigma, splinepoints, scale):
    """Reads file, subtracts background. Returns [compensated image, background]."""
    
    from PIL import Image
    # from pylab import ceil,imshow,show
    import matplotlib.pyplot as plt
    import numpy #,pylab
    from matplotlib.image import pil_to_array
    from filter import canny
    from matplotlib import cm
    import cProfile

    img = Image.open(img)
    if img.mode=='I;16':
        # 16-bit image
        # deal with the endianness explicitly... I'm not sure
        # why PIL doesn't get this right.
        imgdata = np.fromstring(img.tostring(),np.uint8)
        imgdata.shape=(int(imgdata.shape[0]/2),2)
        imgdata = imgdata.astype(np.uint16)
        hi,lo = (0,1) if img.tag.prefix == 'MM' else (1,0)
        imgdata = imgdata[:,hi]*256 + imgdata[:,lo]
        img_size = list(img.size)
        img_size.reverse()
        new_img = imgdata.reshape(img_size)
        # The magic # for maximum sample value is 281
        if img.tag.has_key(281):
            img = new_img.astype(np.float32) / img.tag[281][0]
        elif np.max(new_img) < 4096:
            img = new_img.astype(np.float32) / 4095.
        else:
            img = new_img.astype(np.float32) / 65535.
    else:
        img = pil_to_array(img)
    
    plt.subplot(1,3,1).imshow(img, cmap=cm.Greys_r)
    plt.show()
    
    if len(img.shape)>2:
        raise ValueError('Image must be grayscale')

## Create mask that will fix problem when image has black areas outside of well
    edges = canny(img, np.ones(img.shape, bool), 2, .1, .3)
    ci = np.cumsum(edges, 0)
    cj = np.cumsum(edges, 1)
    i,j = np.mgrid[0:img.shape[0], 0:img.shape[1]]
    mask = ci > 0
    mask = mask & (cj > 0)
    mask[1:,:] &= (ci[0:-1,:] < ci[-1,j[0:-1,:]])
    mask[:,1:] &= (cj[:,0:-1] < cj[i[:,0:-1],-1])
    
    import time
    t0 = time.clock()
    bg = backgr(img, mask, MODE_AUTO, sigma, splinepoints=splinepoints, scale=scale)
    print(("Executed in %f sec" % (time.clock() - t0)))
    bg[~mask] = img[~mask]

    plt.subplot(1,3,2).imshow(img - bg, cmap=cm.Greys_r)
    plt.subplot(1,3,3).imshow(bg, cmap=cm.Greys_r)
    plt.show()
Ejemplo n.º 11
0
    def _openFile(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, "OpenImage", "src", "Bitmaps (*.bmp)")

        if fileName == "":
            h.warn("No file selected.")
            return



        h.log("Loaded!")
        #self.pixmapItem = QtGui.QPixmap(fileName)
        #item = QtGui.QGraphicsPixmapItem(self.pixmapItem)
        #self.scene.addItem(item)

        item = QtGui.QStandardItem(os.path.basename(str(fileName)))
        item.imageFileName = str(fileName)
        orgImg = Image.open(str(fileName), mode='r').convert()
        item.image = MImage.pil_to_array(orgImg.convert('L'))
        item.pixmap = QtGui.QPixmap(fileName)

        #item.setCheckable(True)

        self.model.appendRow(item)
        self.ui.imageListView.setModel(self.model)


        self._checkButtons()
Ejemplo n.º 12
0
def _matplotlib_pil_bug_present():
    """
    Determine whether PIL images should be pre-flipped due to a bug in Matplotlib.

    Prior to Matplotlib 1.2.0, RGB images provided as PIL objects were
    oriented wrongly. This function tests whether the bug is present.
    """

    from matplotlib.image import pil_to_array

    try:
        from PIL import Image
    except:
        import Image

    from astropy import log

    array1 = np.array([[1, 2], [3, 4]], dtype=np.uint8)
    image = Image.fromarray(array1)
    array2 = pil_to_array(image)

    if np.all(array1 == array2):
        log.debug("PIL Image flipping bug not present in Matplotlib")
        return False
    elif np.all(array1 == array2[::-1, :]):
        log.debug("PIL Image flipping bug detected in Matplotlib")
        return True
    else:
        log.warn("Could not properly determine Matplotlib behavior for RGB images - image may be flipped incorrectly")
        return False
Ejemplo n.º 13
0
def getPredictionOfImage(content, names, dates, model=model):
    if content is not None:
        # content = "abcdeghifklmnop"
        img_type = str(content).split("/")[1].replace(";base64,", "")
        img_encoded = str(content).replace(
            str("data:image/" + str(img_type) + ";base64,"), "")
        img_decoded = base64.b64decode(img_encoded)

        # Save the image into a temporary directory
        temp_dir_path = loadImageIntoTempDir(img=img_decoded,
                                             img_type=img_type)

        # Create a generator object based on the contents of the temporary directory
        temp_data_gen, temp_image = createGenObject(temp_dir_path)

        # Assign a grade to the image in the temp dir using the model
        grade = assignPrediction(temp_data_gen, model)

        # Generate the final plot with the predictedgrade
        fname = str(temp_dir_path + "/unlabelled/img." + img_type)
        # img_high_res = mpimg.imread(fname=fname, format=img_type)
        img_high_res = pil_to_array(PIL.Image.open(fname))

        finalPlot = assignImgGrade(img=img_high_res, grade=grade)

        # Clean up and remove the temporary directory
        rmtree(temp_dir_path)

        return finalPlot

    return None
Ejemplo n.º 14
0
def bg_compensate(img, sigma, splinepoints, scale):
    '''Reads file, subtracts background. Returns [compensated image, background].'''
    
    from PIL import Image
    from pylab import ceil,imshow,show
    import numpy,pylab
    from matplotlib.image import pil_to_array
    from filter import canny
    import matplotlib
    import cProfile

    img = Image.open(img)
    if img.mode=='I;16':
        # 16-bit image
        # deal with the endianness explicitly... I'm not sure
        # why PIL doesn't get this right.
        imgdata = np.fromstring(img.tostring(),np.uint8)
        imgdata.shape=(int(imgdata.shape[0]/2),2)
        imgdata = imgdata.astype(np.uint16)
        hi,lo = (0,1) if img.tag.prefix == 'MM' else (1,0)
        imgdata = imgdata[:,hi]*256 + imgdata[:,lo]
        img_size = list(img.size)
        img_size.reverse()
        new_img = imgdata.reshape(img_size)
        # The magic # for maximum sample value is 281
        if img.tag.has_key(281):
            img = new_img.astype(np.float32) / img.tag[281][0]
        elif np.max(new_img) < 4096:
            img = new_img.astype(np.float32) / 4095.
        else:
            img = new_img.astype(np.float32) / 65535.
    else:
        img = pil_to_array(img)
    
    pylab.subplot(1,3,1).imshow(img, cmap=matplotlib.cm.Greys_r)
    pylab.show()
    
    if len(img.shape)>2:
        raise ValueError('Image must be grayscale')

## Create mask that will fix problem when image has black areas outside of well
    edges = canny(img, np.ones(img.shape, bool), 2, .1, .3)
    ci = np.cumsum(edges, 0)
    cj = np.cumsum(edges, 1)
    i,j = np.mgrid[0:img.shape[0], 0:img.shape[1]]
    mask = ci > 0
    mask = mask & (cj > 0)
    mask[1:,:] &= (ci[0:-1,:] < ci[-1,j[0:-1,:]])
    mask[:,1:] &= (cj[:,0:-1] < cj[i[:,0:-1],-1])
    
    import time
    t0 = time.clock()
    bg = backgr(img, mask, MODE_AUTO, sigma, splinepoints=splinepoints, scale=scale)
    print ("Executed in %f sec" % (time.clock() - t0))
    bg[~mask] = img[~mask]

    pylab.subplot(1,3,2).imshow(img - bg, cmap=matplotlib.cm.Greys_r)
    pylab.subplot(1,3,3).imshow(bg, cmap=matplotlib.cm.Greys_r)
    pylab.show()
Ejemplo n.º 15
0
def get_img_trasi_aphrodite_score_triple(image, model):
    image_array = mpimg.pil_to_array(image)
    image_array = np.asarray(image_array)
    image_array = image_array[:, :, 0:3]
    image_array = image_array / 255
    image_array = np.expand_dims(image_array, 0)
    aphrodite_score = model.predict(image_array)
    return image, get_trasi_score(image), aphrodite_score
Ejemplo n.º 16
0
 def get_patch(self):
     i = random.randint(0, self.data_n - 1)
     patch = Image.open((os.path.join(self.data_path, self.data_directory[i])))
     im_width, im_height = patch.size
     window_x = np.random.randint(im_width - self.patch_size[0])
     window_y = np.random.randint(im_height - self.patch_size[1])
     window = patch.crop((window_x, window_y, window_x + self.patch_size[0], window_y + self.patch_size[1]))
     patch_array = mpimage.pil_to_array(window)
     return patch_array
Ejemplo n.º 17
0
    def read_file(self,filename):
        im = Image.open(os.path.join("E:\年龄识别\MORPH数据库\imc_Im100_100\image17",filename),'r')#打开一个图像
        site=filename.find('.')
        label_arr = np.array([int(filename[site-2:site])])
        # 将图像的RGB分离
        r, g, b = im.split()
        # 将PILLOW图像转成数组
        r_arr = plimg.pil_to_array(r)
        g_arr = plimg.pil_to_array(g)
        b_arr = plimg.pil_to_array(b)

        # 将200*240二维数组转成48000的一维数组
        r_arr1 = r_arr.reshape(10000)
        g_arr1 = g_arr.reshape(10000)
        b_arr1 = b_arr.reshape(10000)
        # 3个一维数组合并成一个一维数组,大小为144000
        arr = np.concatenate((r_arr1, g_arr1, b_arr1))
        return arr,label_arr
Ejemplo n.º 18
0
 def on_activated(self, action, x1, y1, x2, y2):
     if x1 and y1 and x2 and y2:
         if action == 'Crop':
             self.dx1.append(x1)
             self.dy1.append(y1)
             self.dx2.append(self.imgWidth - x2)
             self.dy2.append(y1)
             self.dx3.append(x1)
             self.dy3.append(self.imgHeight - y2)
             self.dx4.append(self.imgWidth - x2)
             self.dy4.append(self.imgHeight - y2)
             self.stackImgArr.append(self.imgArr)
             self.dx_dy['topLeft'] = [sum(self.dx1), sum(self.dy1)]
             self.dx_dy['topRight'] = [self.refImgWidth - sum(self.dx2), sum(self.dy2)]
             self.dx_dy['bottomLeft'] = [sum(self.dx3), self.refImgHeight - sum(self.dy3)]
             self.dx_dy['bottomRight'] = [self.refImgWidth - sum(self.dx4), self.refImgHeight - sum(self.dy4)]
             self.img['src'] = self.img['src'].crop((int(x1), int(y1), int(x2), int(y2)))
             self.imgWidth, self.imgHeight = self.img['src'].size
             self.imgArr = mpimg.pil_to_array(self.img['src'])
             self.imgArr.setflags(write=True)
             self.refresh_Img_plot(self.img)
             self.draw()
             self.set_init_coords()
         elif action == 'Delete':
             x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
             ImgArrCopy = deepcopy(self.imgArr)
             self.stackImgArr.append(ImgArrCopy)
             self.imgArr[y1:y2, x1:x2] = 0
             self.img['src'] = Image.fromarray(self.imgArr)
             self.dx1.append(0)
             self.dx2.append(0)
             self.dx3.append(0)
             self.dx4.append(0)
             self.dy1.append(0)
             self.dy2.append(0)
             self.dy3.append(0)
             self.dy4.append(0)
             self.refresh_Img_plot(self.img)
             self.draw()
             self.set_init_coords()
     if action == 'Revert': #TODO: revert should store only changes to image array
         if self.stackImgArr:
             self.imgArr = self.stackImgArr[-1]
             self.img['src'] = Image.fromarray(self.imgArr)
             self.stackImgArr = self.stackImgArr[:-1]
             self.imgWidth, self.imgHeight = self.img['src'].size
             del self.dx1[-1]
             del self.dx2[-1]
             del self.dx3[-1]
             del self.dx4[-1]
             del self.dy1[-1]
             del self.dy2[-1]
             del self.dy3[-1]
             del self.dy4[-1]
             self.profImshow()
             self.draw()
Ejemplo n.º 19
0
 def refresh_Img_plot(self, img):
     self.ax.cla()
     self.img = img
     self.imgArr = mpimg.pil_to_array(self.img['src'])
     self.imgArr.setflags(write=True)
     self.profImshow()
     self.ax.set_title(self.img['pltTitle'])
     self.ax.callbacks.connect('xlim_changed', self.on_xlims_change)
     self.ax.callbacks.connect('ylim_changed', self.on_ylims_change)
     self.fig.canvas.draw_idle()
Ejemplo n.º 20
0
 def ask_for_removal(self, image):
     if image is None:
         ans = input(
             'Cannot display image unfortunately. Shall we try to remove it or not? y/n: '
         ).lower()
     else:
         plt.imshow(mpImage.pil_to_array(image))
         plt.show(block=False)
         ans = input('Should we remove this image? y/n: ').lower()
     return ans == 'y'
Ejemplo n.º 21
0
def read_image(filepath, ratio):
    im = Image.open(filepath)
    (length, height) = im.size
    im = im.resize((length // ratio, height // ratio))
    print(im)
    # im.save('cymsbsbsbsb.png')
    imarr = plimg.pil_to_array(im)
    imarr.flags.writeable = True
    graph_normalization(imarr, length // ratio, height // ratio)
    return (imarr, length // ratio, height // ratio)
Ejemplo n.º 22
0
    def read_file(self, filename):
        im = Image.open(os.path.join("image_test1", filename), 'r')  #打开一个图像
        #site=filename.find('.')
        #label_arr = np.array([int(filename[site-2:site])])
        #label_arr = np.array([int(filename[0])])
        # 将图像的RGB分离
        r, g, b = im.split()
        # 将PILLOW图像转成数组
        r_arr = plimg.pil_to_array(r)
        g_arr = plimg.pil_to_array(g)
        b_arr = plimg.pil_to_array(b)

        # 将224*224二维数组转成50176的一维数组
        r_arr1 = r_arr.reshape(50176)
        g_arr1 = g_arr.reshape(50176)
        b_arr1 = b_arr.reshape(50176)
        # 3个一维数组合并成一个一维数组,大小为150528
        arr = np.concatenate((r_arr1, g_arr1, b_arr1))
        return arr
Ejemplo n.º 23
0
def applyGaussianFilter(imgMatrix, kernelSize = 7):
    gaussianMatrix = MImage.pil_to_array(Image.new('L', imgMatrix.shape, 0))
    matrix = gkern(kernelSize)
    for i in range(size[1] - (kernelSize - 1)):
        for j in range(size[0] - (kernelSize - 1)):
            iS = i + (kernelSize - 1)/2
            jS = j + (kernelSize - 1)/2
            #print t[i:(i + kernelSize), j:(j + kernelSize)]
            gaussianMatrix[iS, jS] = np.sum(np.multiply(imgMatrix[i:(i + kernelSize), j:(j + kernelSize)], matrix))
            #s[iS, jS] = np.sum(t[i:(i + kernelSize), j:(j + kernelSize)],)/kernelSize**2
    return gaussianMatrix
Ejemplo n.º 24
0
    def read_file(self,filename):
        im = Image.open(os.path.join(r"C:\Users\yy\Desktop\Stock\line\line\line_test",filename),'r')#打开一个图像

        site=filename.find('.')
        label_arr = np.array([int(filename[site-1:site])])
       
        # 将图像的RGB分离
        r, g, b = im.split()
        # 将PILLOW图像转成数组
        r_arr = plimg.pil_to_array(r)
        g_arr = plimg.pil_to_array(g)
        b_arr = plimg.pil_to_array(b)

        # 将200*240二维数组转成48000的一维数组
        r_arr1 = r_arr.reshape(224*224)
        g_arr1 = g_arr.reshape(224*224)
        b_arr1 = b_arr.reshape(224*224)
        # 3个一维数组合并成一个一维数组,大小为144000
        arr = np.concatenate((r_arr1, g_arr1, b_arr1))
        
        return arr,label_arr
Ejemplo n.º 25
0
	def __init__(self, name, add_noise=True, verbose=False):
		""" Class Image constructor
			
			
			Parameters
			----------
			name: str
				Path to the image file
				
			add_noise: Bool, optional, default: True
				Add noise to smooth histograms of highly compressed jpegs
				and palette based images.
			
			verbose: Bool/str, optional, default: False
				Verbosity level:
				- False: silent run
				- True: report textual information
				- Path prefix: report textual information and report graphical
					information in verbose+<suffix>.jpg files
		"""
		self.verbose=verbose
		self.name = name
		self.jpeg_quality = 100
		self.palette_use = 1.
		self.add_noise = add_noise
		with open(name, "rb") as fh:
			image = pil.Image.open(fh)
			
			if image.format == 'JPEG':
				q0 = np.array(image.quantization[0])[zigzag_index].reshape(8, 8)
				if 1 in image.quantization:
					q1 = np.array(image.quantization[1])[zigzag_index].reshape(8, 8)
				else:
					q1 = q0.copy()
					
				S = np.vstack([(100 * q0[:3, :3] - 50)/ijg_q0[:3, :3], (100 * q1[:3, :3] - 50)/ijg_q1[:3, :3]]).max()
				self.jpeg_quality = ((200 - S)/2 if S < 100 else 5000/S)

			if image.mode == 'P':
				csc = np.cumsum(np.array(sorted(image.getcolors(), key=lambda x:x[0]))[:, 0])
				self.palette_use = csc[csc > csc.max()/20.].shape[0]/float(len(csc))
			
			img = pil_to_array(image)
			

		if np.max(img) <= 1:
			img = np.uint8(img*255)
		self.valid = True
		if len(img.shape) < 3 or img.shape[2] < 3:
			self.valid = False
			return
		self.img = img[:, :, :3]
Ejemplo n.º 26
0
def InitImage(image):
    #read PIL image (1-D image) as graph
    #image = Image.open('image.jpg').convert("L")
    img = mpimg.pil_to_array(image)
    plt.figure(figsize=(4, 4))
    plt.imshow(img, cmap='gray')
    G = nx.grid_2d_graph(img.shape[0], img.shape[1])
    #nx.set_node_attributes(G,{u:{'intensity':v} for u,v in np.ndenumerate(img)})

    for u, v, d in G.edges(data=True):
        d['weight'] = 20 - abs(np.subtract(int(img[u]), int(img[v]))) + 0.5

    return G
Ejemplo n.º 27
0
def display(display_list):
    plt.figure(figsize=(8, 8))

    title = ['Input Image', 'True Mask', 'Predicted Mask']

    for i in range(len(display_list)):
        plt.subplot(1, len(display_list), i + 1)
        plt.title(title[i])
        A = tf.keras.preprocessing.image.array_to_img(display_list[i])
        img = np.ma.array(pil_to_array(A))
        plt.imshow(img)
        plt.axis('off')
    plt.show()
Ejemplo n.º 28
0
def applyGaussianFilter(imgMatrix, kernelSize=7):
    gaussianMatrix = MImage.pil_to_array(Image.new('L', imgMatrix.shape, 0))
    matrix = gkern(kernelSize)
    for i in range(size[1] - (kernelSize - 1)):
        for j in range(size[0] - (kernelSize - 1)):
            iS = i + (kernelSize - 1) / 2
            jS = j + (kernelSize - 1) / 2
            #print t[i:(i + kernelSize), j:(j + kernelSize)]
            gaussianMatrix[iS, jS] = np.sum(
                np.multiply(imgMatrix[i:(i + kernelSize), j:(j + kernelSize)],
                            matrix))
            #s[iS, jS] = np.sum(t[i:(i + kernelSize), j:(j + kernelSize)],)/kernelSize**2
    return gaussianMatrix
Ejemplo n.º 29
0
 def read_file(self,filename):
     im = Image.open(os.path.join("./unlabelled/"+filename))#打开一个图像
     im = im.resize((224, 224))
     # 将图像的RGB分离
     r, g, b = im.split()
     # 将PILLOW图像转成数组
     r_arr = plimg.pil_to_array(r)
     g_arr = plimg.pil_to_array(g)
     b_arr = plimg.pil_to_array(b)
     # 将32*32二位数组转成1024的一维数组
     r_arr1 = r_arr.reshape(50176)
     g_arr1 = g_arr.reshape(50176)
     b_arr1 = b_arr.reshape(50176)
     # 标签
     # file_labels = []
     file_label = [0]
     if os.path.exists(os.path.join("Glaucoma+/"+filename)):
         file_label = [1]
         # print("Normal:",filename)
     # file_labels.append(file_label)
     # 3个一维数组合并成一个一维数组,大小为244860+1
     arr = np.concatenate((r_arr1, g_arr1, b_arr1))
     return arr,file_label
Ejemplo n.º 30
0
def _pil_to_array(im):
    """
    Wrapper to handle mod introduced in matplotlib 1.2 that turned array upside down.
    """
    rgb = pil_to_array(im)
    M, m, r = matplotlib.__version__.split('.')
    ver = int(M) * 100 + int(m)
    if ver > 101:  # matplotlib 1.2 and later
        rank = len(rgb.shape)
        if rank == 2:
            rgb = rgb[-1::-1, :]
        else:
            rgb = rgb[-1::-1, :, :]
    return rgb
Ejemplo n.º 31
0
    def read_file(self, filename, classnum):
        #im = Image.open(os.path.join("../Stock/up/up_train/up_%s"%classnum,filename),'r')#打开一个图像
        im = Image.open(
            os.path.join(
                r"C:\Users\yy\Desktop\Stock\line\line\line_train\line_%s" %
                classnum, filename), 'r')  # 打开一个图像
        site = filename.find('.')
        label_arr = np.array([int(filename[site - 1:site])])

        # 将图像的RGB分离
        r, g, b = im.split()
        # 将PILLOW图像转成数组
        r_arr = plimg.pil_to_array(r)
        g_arr = plimg.pil_to_array(g)
        b_arr = plimg.pil_to_array(b)

        # 将224*224二维数组转成50176的一维数组
        r_arr1 = r_arr.reshape(224 * 224)
        g_arr1 = g_arr.reshape(224 * 224)
        b_arr1 = b_arr.reshape(224 * 224)
        # 3个一维数组合并成一个一维数组,大小为150528
        arr = np.concatenate((r_arr1, g_arr1, b_arr1))

        return arr, label_arr
Ejemplo n.º 32
0
 def __init__(self, img, width=5, height=4, dpi=100):
     self.img = img
     self.imgArr = mpimg.pil_to_array(self.img['src'])
     self.imgArr.setflags(write=True)
     self.stackImgArr = []
     self.limX = ()
     self.limY = ()
     self.fig = plt.figure(figsize=(width, height), dpi=dpi)
     self.ax = self.fig.add_subplot(111)
     self.ax.set_title(self.img['pltTitle'])
     self.ax.callbacks.connect('xlim_changed', self.on_xlims_change)
     self.ax.callbacks.connect('ylim_changed', self.on_ylims_change)
     FigureCanvas.__init__(self, self.fig)
     self.set_init_coords()
     self.initCropCoords(img)
     self.plot()
Ejemplo n.º 33
0
 def frames(self, count=0):
     """
     Return iterator over frames.
     
     The composition of functions in `self.fns`
     list is applied to each frame. By default, this list is empty. Examples
     of function "hooks" to put into `self.fns` are functions from ``scipy.ndimage``.
     """
     fn = self.pipeline()
     while True:
         try:
             self.im.seek(count)
             count += 1
             yield fn(mpl_img.pil_to_array(self.im))
         except EOFError:
             break
Ejemplo n.º 34
0
def save_diff(images):
    tmp = images.copy()
    for k in range(len(images)):
        imagename = "./save/" + str(k) + ".jpg"
        plt.imsave(imagename,
                   images[k].reshape(28, 28),
                   vmin=0,
                   vmax=255,
                   format="jpg",
                   cmap='gray')

    for k in range(len(images)):
        imagename = "./save/" + str(k) + ".jpg"
        image = Image.open(imagename, mode='r').convert('L')
        im_array = mp.pil_to_array(image)
        tmp[k] = im_array
    return tmp
Ejemplo n.º 35
0
def image2map(image, lmax=10):
    """Return a map vector corresponding to a lat-long map image."""
    # If image doesn't exist, check for it in maps directory
    if not os.path.exists(image):
        dn = os.path.dirname
        image = os.path.join(dn(os.path.abspath(__file__)), image + ".jpg")
        if not os.path.exists(image):
            raise ValueError("File not found: %s." % image)

    # Get the image array
    grayscale_pil_image = Image.open(image).convert("L")
    image_array = pil_to_array(grayscale_pil_image)
    image_array = np.array(image_array, dtype=float)
    image_array /= np.max(image_array)

    # Convert it to a map
    return array2map(image_array, lmax=lmax)
Ejemplo n.º 36
0
 def on_file_open(self, event):
     dlg = wx.FileDialog(self.frame, style=wx.FD_OPEN)
     if dlg.ShowModal() == wx.ID_OK:
         img = pil_to_array(
             PILImage.open(
                 os.path.join(dlg.GetDirectory(), dlg.GetFilename())))
         if img.ndim == 3:
             img = img[:, :, 0] + img[:, :, 1] + img[:, :, 2]
         img = stretch(img.astype(float))
         lt = self.frame.MenuBar.Menus[0][0].MenuItems[7].IsChecked()
         if lt:
             limg, d = log_transform(img)
         else:
             limg = img
         self.frame.subplot_imshow_grayscale(0, 0, limg)
         limg = limg.flatten()
         menu_items = self.frame.MenuBar.Menus[0][0].MenuItems
         if menu_items[2].IsChecked():
             t1 = t2 = otsu(limg)
         elif menu_items[3].IsChecked():
             t1 = t2 = entropy(limg)
         elif menu_items[4].IsChecked():
             t1, t2 = otsu3slow(limg)
         elif menu_items[5].IsChecked():
             t1, t2 = entropy3(limg)
         else:
             t1, t2 = otsu3(limg)
         if lt:
             t1, t2 = inverse_log_transform(np.array([t1, t2]), d)
         m1 = img < t1
         m2 = np.logical_and(img >= t1, img < t2)
         m3 = img > t2
         cimg = np.zeros((m1.shape[0], m1.shape[1], 3))
         cimg[:, :, 0][m1] = img[m1]
         cimg[:, :, 1][m2] = img[m2]
         cimg[:, :, 2][m3] = img[m3]
         self.frame.subplot_imshow(1,
                                   0,
                                   cimg,
                                   sharex=self.frame.subplot(0, 0),
                                   sharey=self.frame.subplot(0, 0))
         self.frame.Refresh()
         wx.MessageBox("Low threshold = %f, high threshold = %f" %
                       (t1, t2),
                       parent=self.frame)
Ejemplo n.º 37
0
def test_load():
    """Test that we're loading images correctly."""
    # Get the image directly
    image = os.path.join(os.path.dirname(starry.__file__), "img", "spot.png")
    grayscale_pil_image = Image.open(image).convert("L")
    img1 = pil_to_array(grayscale_pil_image)
    img1 = np.array(img1, dtype=float)
    img1 /= 255.0  # to [0, 1] range
    img1 = np.flipud(img1)  # align
    img1 = img1[:, ::2]  # make square to match starry output

    # Render the image with starry at high res
    map = starry.Map(30)
    map.load("spot", extent=(-180, 179, -90, 89))
    img2 = map.render(projection="rect", res=img1.shape[0])

    # Canny filter on both images to detect edges
    img1 = np.array(canny(img1, sigma=4), dtype=int)
    img2 = np.array(canny(img2, sigma=4), dtype=int)

    # Compute the difference between the images
    # Do this several times by translating one of
    # the images by a single pixel and computing
    # the *minimum*. This has the effect of allowing
    # a one-pixel tolerance in the comparison
    diff = np.min(
        np.abs([
            img2 - img1,
            img2 - shift(img1, [0, 1]),
            img2 - shift(img1, [0, -1]),
            img2 - shift(img1, [1, 0]),
            img2 - shift(img1, [-1, 0]),
        ]),
        axis=0,
    )

    # Number of pixels in the image edges
    pixels = np.count_nonzero(img1)

    # Number of pixels that differ between the two
    pixels_diff = np.count_nonzero(diff)

    # There should be VERY few pixels in the difference image
    assert pixels_diff / pixels < 0.01
Ejemplo n.º 38
0
 def on_file_open(self, event):
     dlg = wx.FileDialog(self.frame,style=wx.FD_OPEN)
     if dlg.ShowModal() == wx.ID_OK:
         img = pil_to_array(PILImage.open(os.path.join(dlg.GetDirectory(),dlg.GetFilename())))
         if img.ndim == 3:
             img = img[:,:,0]+img[:,:,1]+img[:,:,2]
         img = stretch(img.astype(float))
         lt = self.frame.MenuBar.Menus[0][0].MenuItems[7].IsChecked()
         if lt:
             limg, d = log_transform(img)
         else:
             limg = img
         self.frame.subplot_imshow_grayscale(0, 0, limg)
         limg = limg.flatten()
         menu_items = self.frame.MenuBar.Menus[0][0].MenuItems
         if menu_items[2].IsChecked():
             t1 = t2 = otsu(limg)
         elif menu_items[3].IsChecked():
             t1 = t2 = entropy(limg)
         elif menu_items[4].IsChecked():
             t1, t2 = otsu3slow(limg)
         elif menu_items[5].IsChecked():
             t1, t2 = entropy3(limg)
         else:
             t1, t2 = otsu3(limg)
         if lt:
             t1,t2 = inverse_log_transform(np.array([t1,t2]), d)
         m1 = img < t1
         m2 = np.logical_and(img >= t1, img < t2)
         m3 = img > t2
         cimg = np.zeros((m1.shape[0],m1.shape[1],3))
         cimg[:,:,0][m1]=img[m1]
         cimg[:,:,1][m2]=img[m2]
         cimg[:,:,2][m3]=img[m3]
         self.frame.subplot_imshow(1, 0, cimg,
                                   sharex = self.frame.subplot(0,0),
                                   sharey = self.frame.subplot(0,0))
         self.frame.Refresh()
         wx.MessageBox("Low threshold = %f, high threshold = %f"%(t1,t2),
                       parent=self.frame)
Ejemplo n.º 39
0
    def _gaussFilter(self):
        kernelSize = 7
        imgMatrix = self.selectedItem.image
        size = imgMatrix.shape
        gaussianMatrix = MImage.pil_to_array(Image.new('L', imgMatrix.shape, 0))
        matrix = gkern(kernelSize)
        for i in range(size[1] - (kernelSize - 1)):
            for j in range(size[0] - (kernelSize - 1)):
                iS = i + (kernelSize - 1)/2
                jS = j + (kernelSize - 1)/2
                #print t[i:(i + kernelSize), j:(j + kernelSize)]
                gaussianMatrix[iS, jS] = np.sum(np.multiply(imgMatrix[i:(i + kernelSize), j:(j + kernelSize)], matrix))
                #s[iS, jS] = np.sum(t[i:(i + kernelSize), j:(j + kernelSize)],)/kernelSize**2

        item = QtGui.QStandardItem("new")
        item.imageFileName = None


        item.image = gaussianMatrix
        Image.fromarray(gaussianMatrix).save("bliblop", "BMP")
        item.pixmap = QtGui.QPixmap("bliblop")

        self.model.appendRow(item)
        self.ui.imageListView.setModel(self.model)
Ejemplo n.º 40
0
import pylab as P
from matplotlib.toolkits.basemap import Basemap
from matplotlib.numerix import ma
from matplotlib.image import pil_to_array
from PIL import Image

# shows how to warp an image from one map projection to another.
# image from http://visibleearth.nasa.gov/

# read in jpeg image to rgba array of normalized floats.
pilImage = Image.open('land_shallow_topo_2048.jpg')
rgba = pil_to_array(pilImage)
rgba = rgba.astype(P.Float32)/255. # convert to normalized floats.

# define lat/lon grid that image spans (projection='cyl').
nlons = rgba.shape[1]; nlats = rgba.shape[0]
delta = 360./float(nlons)
lons = P.arange(-180.+0.5*delta,180.,delta)
lats = P.arange(-90.+0.5*delta,90.,delta)

# create new figure
fig=P.figure()
# define cylindrical equidistant projection.
m = Basemap(projection='cyl',llcrnrlon=-180,llcrnrlat=-90,urcrnrlon=180,urcrnrlat=90,resolution='l')
# plot (unwarped) rgba image.
im = m.imshow(rgba)
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
# draw lat/lon grid lines.
m.drawmeridians(P.arange(-180,180,60),labels=[0,0,0,1],color='0.5')
m.drawparallels(P.arange(-90,90,30),labels=[1,0,0,0],color='0.5')
Ejemplo n.º 41
0
    print "DONE"
    return image


#######################################

print "Loading and Converting Image ...",
orgImg = Image.open("src/" + orgFileName, mode = 'r').convert()

try:
    orgImg = orgImg.convert().crop((0,0,size[0],size[1]))
except NameError:
    size = orgImg.size


orgGreyscaleMatrix = MImage.pil_to_array(orgImg.convert('L'))

emptyGreyscaleMatrix = MImage.pil_to_array(Image.new('L', size, 0))
emptyColoredMatrix = MImage.pil_to_array(Image.new('RGB', size, (0,0,0)))
print "DONE"


# print "Compute the 2-dimensional FFT ...",
# #print "."
# m = np.fft.rfft2(orgGreyscaleMatrix)
# #print m.shape
# #print m
# #print np.amax(m)
# am = np.log(np.absolute(m)+1)
# mm = np.around(am/np.amax(am)*255, decimals=0).astype(np.uint8)
# print "DONE"
Ejemplo n.º 42
0
    def test_02_01_compare_to_matlab(self):
        path = os.path.split(__file__)[0]
        mask_file = os.path.join(path, 'Channel2-01-A-01Mask.png')
        mask = pil_to_array(PILImage.open(mask_file))
        mask = np.flipud(mask)
        texture_measurements = loadmat(os.path.join(path,'texturemeasurements.mat'), struct_as_record=True)
        texture_measurements = texture_measurements['m'][0,0]
        image_file = os.path.join(example_images_directory(), 
                                  'ExampleSBSImages', 'Channel1-01-A-01.tif')
        image = pil_to_array(PILImage.open(image_file))
        image = np.flipud(image[:,:,0])
        image = image.astype(float) / 255.0
        labels,count = scind.label(mask.astype(bool),np.ones((3,3),bool))
        centers = scind.center_of_mass(np.ones(labels.shape), labels, 
                                       np.arange(count)+1)
        centers = np.array(centers)
        X = 1 # the index of the X coordinate
        Y = 0 # the index of the Y coordinate
        order_python = np.lexsort((centers[:,X],centers[:,Y]))
        workspace, module = self.make_workspace(image, labels, convert = False)
        module.scale_groups[0].scale.value = 3
        my_angle = M.H_HORIZONTAL
        module.scale_groups[0].angles.value = my_angle

        module.run(workspace)
        m = workspace.measurements
        tm_center_x = texture_measurements['Location_Center_X'][0,0][:,0]
        tm_center_y = texture_measurements['Location_Center_Y'][0,0][:,0]
        order_matlab = np.lexsort((tm_center_x,tm_center_y))
            
        for measurement in M.F_HARALICK:
            mname = '%s_%s_%s_%d'%(M.TEXTURE, measurement, INPUT_IMAGE_NAME, 3)
            pymname = mname + "_" + M.H_TO_A[my_angle]
            pytm = m.get_current_measurement(INPUT_OBJECTS_NAME, pymname)
            tm = texture_measurements[mname][0,0][:,]
            error_count = 0
            for i in range(count):
                matlab_val = tm[order_matlab[i]]
                python_val = pytm[order_python[i]]
                self.assertAlmostEqual(tm[order_matlab[i]],
                                       pytm[order_python[i]],7,
                                       "Measurement = %s, Loc=(%.2f,%.2f), Matlab=%f, Python=%f"%
                                       (mname, tm_center_x[order_matlab[i]],
                                        tm_center_y[order_matlab[i]],
                                        tm[order_matlab[i]],
                                        pytm[order_python[i]]))
        image_measurements =\
        (('Texture_AngularSecondMoment_Cytoplasm_3', 0.5412),
         ('Texture_Contrast_Cytoplasm_3',0.1505),
         ('Texture_Correlation_Cytoplasm_3', 0.7740),
         ('Texture_Variance_Cytoplasm_3', 0.3330),
         ('Texture_InverseDifferenceMoment_Cytoplasm_3',0.9321),
         ('Texture_SumAverage_Cytoplasm_3',2.5684),
         ('Texture_SumVariance_Cytoplasm_3',1.1814),
         ('Texture_SumEntropy_Cytoplasm_3',0.9540),
         ('Texture_Entropy_Cytoplasm_3',1.0677),
         ('Texture_DifferenceVariance_Cytoplasm_3',0.1314),
         ('Texture_DifferenceEntropy_Cytoplasm_3',0.4147),
         ('Texture_InfoMeas1_Cytoplasm_3',-0.4236),
         ('Texture_InfoMeas2_Cytoplasm_3',0.6609))
        for feature_name, value in image_measurements:
            py_feature_name = feature_name + "_" + M.H_TO_A[my_angle]
            pytm = m.get_current_image_measurement(py_feature_name)
            self.assertAlmostEqual(pytm, value,3,
                                   "%s failed. Python=%f, Matlab=%f" %
                                   (feature_name, pytm, value))
Ejemplo n.º 43
0
Dependencies: Matplotlib, Basemap toolkit, Python Imaging Library

"""
from PIL import Image
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import pil_to_array

plot_name = 'geos_demo.png'
overlay_color = 'black'

# read in jpeg image to rgb array
pilImage = Image.open('200706041200-msg-ch01-SAfrica.jpg')
#data = asarray(pilImage)
data = pil_to_array(pilImage)
data = data[:, :, 0] # get data from first channel in the image

# define data region and projection parameters
ll_lon = 9.74
ll_lat = -35.55
ur_lon = 48.45
ur_lat = 0.2
lon_0 = 0.0
satellite_height = 35785831.0

fig = plt.figure(figsize=(7,7))
ax = fig.add_axes((0.1,0.1,0.8,0.8))
# create Basemap instance for a Geostationary projection.
m = Basemap(projection='geos', lon_0=lon_0, satellite_height=satellite_height,
            resolution='l', llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat)