Example #1
0
def user_color(original, new):
    '''There are two parameters. Original is the original image that has yet to 
    be modified. New is the image after it has been modified. First the image is
    opened, and then there is raw input so that the user can input what color of
    the border that they want and the size of the border. There is a try and 
    except structure used to by pass error so that the program still works even 
    though you enter an invalid value. The image with the customized border is 
    returned'''
    img = Image.open(original)  #opens original image
    #adds border to original
    color = raw_input('What color would you like the border to be?(Prompt \
will appear until all images have a chosen color.): \n')
    thickness = raw_input(
        'What width(in pixels) would you like the border to be? \
Please type an INTEGER!(Prompt will appear until all images are have a chosen\
width.): \n')
    try:
        img_with_border = ImageOps.expand(img,
                                          border=int(thickness),
                                          fill=str(color))
    except ValueError:
        img_with_border = ImageOps.expand(img,
                                          border=int(30),
                                          fill=str("blue"))

    return img_with_border
Example #2
0
def processOneImage(imageFile, imageLabel):

    image  = Image.open(imageFile, "rb");

    buffer = np.array(image);

    IMAGE_WIDTH   = string.atoi(G_OPTION.getValue("width"));
    IMAGE_HEIGHT  = string.atoi(G_OPTION.getValue("height"));
    IMAGE_CHANNEL = string.atoi(G_OPTION.getValue("channel"));

    buffer = buffer.reshape([IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNEL])

    mode = G_OPTION.getValue("mode")

    for char in mode:
        if(char == 'm'):
            #substract
            buffer=subtractmean(buffer)
            return
        else:
            #normalize
            if(char == 'n'):
                return
            else:
                #whitening
                if(char == "w"):
                    return
                else:
                    if(char == "c"):
                        return
Example #3
0
	def update(self):
		if isinstance(self.line,matplotlib.image.AxesImage):
			# image name
			try:
				if len(self.xdata)==0 and self.dataName: self.xdata=self.imgData[self.dataName]  # empty list reference an empty singleton, not the list we want; adjust here
				import Image
				if self.xdata[current]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
				else: img=Image.open(self.xdata[current])
				self.line.set_data(img)
			except IndexError: pass
		else:
			# regular data
			import numpy
			# current==-1 avoids copy slicing data in the else part
			if current==None or current==-1 or afterCurrentAlpha==1:
				self.line.set_xdata(self.xdata); self.line.set_ydata(self.ydata)
				self.line2.set_xdata([]); self.line2.set_ydata([])
			else:
				try: # try if we can extend the first part by one so that lines are connected
					self.xdata[:current+1]; preCurrEnd=current+1
				except IndexError: preCurrEnd=current
				preCurrEnd=current+(1 if len(self.xdata)>current else 0)
				self.line.set_xdata(self.xdata[:preCurrEnd]); self.line.set_ydata(self.ydata[:preCurrEnd])
				self.line2.set_xdata(self.xdata[current:]); self.line2.set_ydata(self.ydata[current:])
			try:
				x,y=self.xdata[current],self.ydata[current]
			except IndexError: x,y=0,0
			# this could be written in a nicer way, very likely
			try:
				pt=numpy.ndarray((2,),buffer=numpy.array([float(x),float(y)]))
				if self.scatter:
					self.scatter.set_offsets(pt)
					# change rotation of the marker (possibly incorrect)
					try:
						dx,dy=self.xdata[current]-self.xdata[current-1],self.ydata[current]-self.ydata[current-1]
						# smoothing from last n values, if possible
						# FIXME: does not show arrow at all if less than window values
						#try:
						#	window=10
						#	dx,dy=[numpy.average(numpy.diff(dta[current-window:current])) for dta in self.xdata,self.ydata]
						#except IndexError: pass
						# there must be an easier way to find on-screen derivative angle, ask on the matplotlib mailing list
						axes=self.line.get_axes()
						p=axes.patch; xx,yy=p.get_verts()[:,0],p.get_verts()[:,1]; size=max(xx)-min(xx),max(yy)-min(yy)
						aspect=(size[1]/size[0])*(1./axes.get_data_ratio())
						angle=math.atan(aspect*dy/dx)
						if dx<0: angle-=math.pi
						self.scatter.set_transform(matplotlib.transforms.Affine2D().rotate(angle))
					except IndexError: pass
				if self.annotation:
					if math.isnan(x) or math.isnan(y):
						if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y)
						else: self.annotation.xytext=(0,0)
						self.annotation.set_text('') # make invisible, place anywhere
					else:
						#
						if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y) # newer MPL versions (>=1.4)
						else: self.annotation.xyann=(x,y)
						self.annotation.set_text(self.annotation.annotateFmt.format(xy=(float(x),float(y))))
			except TypeError: pass # this happens at i386 with empty data, saying TypeError: buffer is too small for requested array
Example #4
0
def gray_scale(original, new):
    '''There are two parameters. Original is the original image that has yet to 
    be modified. New is the image after it has been modified. First, we open the
    images that aren't modified yet, and then, we open the logo. We use imageOps 
    to change the image into grayscale and then we paste the logo onto the 
    image. We don't set the logo equal to the mask because we want the logo to 
    have a black background. After the logo is pasted, we return the image with 
    the pasted logo and grayscale'''
    image_file = Image.open(original)  # open colour image
    img = Image.open('ourlogo.png')
    grayscale = ImageOps.grayscale(image_file)

    width, height = grayscale.size
    logo_small = img.resize((78, 86))
    grayscale.paste(logo_small, (width - 90, 5))

    return grayscale
def ExtractData(Nom):  # Renvoie un tableau H*L*3
    im = Image.open(Nom)  # Lecture de l’image
    L, H = im.size  # Taille de l’image
    data = im.getdata()  # On récupère les données dans la variable data
    d = np.array(data)  # conversion de data en tableau
    IMA = d.reshape(
        (H, L, 3))  # On transforme un tableau 1D en tableau avec 3 indices.
    return IMA  # Renvoie un tableau de dimension H*L*3
Example #6
0
 def __getitem__(self, item):
     sample = {
         'image':
         self.transform(Image.open(self.images[item]).convert('RGB'))
     }
     if self.labels is not None:
         sample['label'] = self.labels[item]
         sample['attributes'] = self.attributes[sample['label']]
         sample['word_embeddings'] = self.word_embeddings[sample['label']]
     return sample
Example #7
0
 def load_test(path):
     resize_trans=transforms.Compose([transforms.Resize(size=(60,60)),transforms.ToTensor()])
     if not os.path.exists(path):
         print('File {} doesnt exist'.format(path))
     else:   
         img = Image.open(path)
         img = img.convert(mode='L')
         img = resize_trans(img)
         x = img.view(1,1,60,60)
         return(img.view(60,60).numpy(),x)
Example #8
0
def process_image(image):
    img_transforms = transforms.Compose([
        transforms.Resize(255),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

    img = img_transforms(Image.open(image))
    return img
Example #9
0
    def run(self):
        figwidth = self.options.pop('figwidth', None)
        figclasses = self.options.pop('figclass', ["right"])
        align = self.options.pop('align', None)
        (media_node, ) = Media.run(self)
        if isinstance(media_node, nodes.system_message):
            return [media_node]
        figure_node = nodes.figure('', media_node)
        if figwidth == 'image':
            if PIL and self.state.document.settings.file_insertion_enabled:
                # PIL doesn't like Unicode paths:
                try:
                    i = PIL.open(str(media_node['uri']))
                except (IOError, UnicodeError):
                    pass
                else:
                    self.state.document.settings.record_dependencies.add(
                        media_node['uri'])
                    figure_node['width'] = i.size[0]
        elif figwidth is not None:
            figure_node['width'] = figwidth
        if figclasses:
            figure_node['classes'] += figclasses
        if align:
            figure_node['align'] = align
        if self.content:
            node = nodes.Element()  # anonymous container for parsing
            self.state.nested_parse(self.content, self.content_offset, node)
            first_node = node[0]
            if isinstance(first_node, nodes.paragraph):
                caption = nodes.caption(first_node.rawsource, '',
                                        *first_node.children)
                figure_node += caption
            elif not (isinstance(first_node, nodes.comment)
                      and len(first_node) == 0):
                error = self.state_machine.reporter.error(
                    'Figure caption must be a paragraph or empty comment.',
                    nodes.literal_block(self.block_text, self.block_text),
                    line=self.lineno)
                return [figure_node, error]
            if len(node) > 1:
                figure_node += nodes.legend('', *node[1:])
        node = figure_node

        node['label'] = self.options.get('label', None)
        if not node['label']:
            node['label'] = self.options.get('uri')
        node['number'] = None
        ret = [node]
        if node['label']:
            key = node['label']
            tnode = nodes.target('', '', ids=['figure-' + node['label']])
            self.state.document.note_explicit_target(tnode)
            ret.insert(0, tnode)
        return ret
Example #10
0
def multi_border(originalimg, new):
    ''' Module for adding borders to images in folders '''

    img = Image.open(originalimg)  #opens original image
    #adds border to original
    img_with_border1 = ImageOps.expand(img, border=30, fill='blue')
    img_with_border2 = ImageOps.expand(img_with_border1,
                                       border=30,
                                       fill='white')
    img_with_border3 = ImageOps.expand(img_with_border2, border=30, fill='red')

    return img_with_border3
Example #11
0
def imgSizeChanger(size, file_name, new_file_name):
    new_img = Image.new("RGB", size, "white")
    im = Image.open(file_name)
    im.thumbnail(size, Image.ANTIALIAS)
    load_img = im.load()
    load_newimg = new_img.load()
    i_offset = (size - im.size[0]) / 2
    j_offset = (size - im.size[1]) / 2
    for i in range(0, im.size[0]):
        for j in range(0, im.size[1]):
            load_newimg[i + i_offset, j + j_offset] = load_img[i, j]
    new_img.save(new_file_name, "JPEG")
Example #12
0
def multi_border(original, new):
    '''There are two parameters. Original is the original image that has yet to 
    be modified. New is the image after it has been modified. First, the 
    function upens the image, and then wit ImageOps, three borders are made by 
    adding a border around the image three times. One is red, one is blue and 
    one is white. Then, the logo image is opened and it is pasted onto the image 
    with three borders after it is resized to a smaller scale. The mask is set 
    to the logo because if it isn't, the png would have a black background'''
    img = Image.open(original)  #opens original image
    #adds border to original
    img_with_border1 = ImageOps.expand(img, border=30, fill='blue')
    img_with_border2 = ImageOps.expand(img_with_border1,
                                       border=30,
                                       fill='white')
    img_with_border3 = ImageOps.expand(img_with_border2, border=30, fill='red')

    width, height = img_with_border3.size
    img = Image.open('ourlogo.png')
    logo_small = img.resize((78, 86))
    img_with_border3.paste(logo_small, (width - 190, 90), mask=logo_small)

    return img_with_border3
Example #13
0
def distorted_colored(original, new):
    '''There are two parameters. Original is the original image that has yet to 
    be modified. New is the image after it has been modified. First the image is
    opened, and then, with ImageOps, and assigning variables specific colors, we
    are able to colorize the image into a red and blue image that makes it have 
    some wierd and distorted colors. The red and blue colored image is 
    returned'''
    image_file = Image.open(original)  # open colour image
    grayscale = ImageOps.grayscale(image_file)
    BLUE = "#0000FF"
    RED = "#FF0000"
    distorted_pic = ImageOps.colorize(grayscale, RED, BLUE)

    return distorted_pic
	def calculate(self, imgs):
		try:
			img1 = Image.open(str(imgs[0]))
			img2 = Image.open(str(imgs[1]))


			if img1.size != img2.size or img1.getbands() != img2.getbands():
				return -1

			s = 0
			for band_index, band in enumerate(img1.getbands()):
				m1 = np.array([p[band_index] for p in img1.getdata()]).reshape(*img1.size)
				m2 = np.array([p[band_index] for p in img2.getdata()]).reshape(*img2.size)
				s += np.sum(np.abs(m1-m2))
			s = s/1000000

			(filepath1, filename1) = os.path.split(str(imgs[0]))
			(filepath2, filename2) = os.path.split(str(imgs[1]))
			label = filename1 + "-" + filename2

			return (label, s)
		except Exception, e:
			QMessageBox.warning(self, "Messaggio", str(e), QMessageBox.Ok)
Example #15
0
    def calculate(self, imgs):
        try:
            img1 = Image.open(str(imgs[0]))
            img2 = Image.open(str(imgs[1]))

            if img1.size != img2.size or img1.getbands() != img2.getbands():
                return -1

            s = 0
            for band_index, band in enumerate(img1.getbands()):
                m1 = np.array([p[band_index]
                               for p in img1.getdata()]).reshape(*img1.size)
                m2 = np.array([p[band_index]
                               for p in img2.getdata()]).reshape(*img2.size)
                s += np.sum(np.abs(m1 - m2))
            s = s / 1000000

            (filepath1, filename1) = os.path.split(str(imgs[0]))
            (filepath2, filename2) = os.path.split(str(imgs[1]))
            label = filename1 + "-" + filename2

            return (label, s)
        except Exception as e:
            QMessageBox.warning(self, "Messaggio", str(e), QMessageBox.Ok)
Example #16
0
def border_one(original_image, percent_of_side=.3):
    """There are two parameters, original_image represents the image before it 
    is modified, and percent_of_side is set to .3. There is a border that is 
    made with masks that are transparent so that you can see the brown canvas 
    behind the image. Our logo of the image is then pasted onto the bordered 
    image, and then it is returned"""
    #set the radius of the rounded corners
    width, height = original_image.size

    ###
    #create a mask
    ###

    #start with transparent mask
    border_mask = PIL.Image.new('RGBA', (width, height), (127, 0, 127, 0))
    drawing_layer = PIL.ImageDraw.Draw(border_mask)

    # Overwrite the RGBA values with A=255.
    # The 127 for RGB values was used merely for visualizing the mask

    # Draw two rectangles to fill interior with opaqueness
    drawing_layer.polygon([(0, 0), (width, 0), (width, height), (0, height)],
                          fill=(127, 0, 127, 150))

    drawing_layer.polygon([(0, 0), (30, 0), (30, height), (0, height)],
                          fill=(0, 0, 255, 0),
                          outline=(0, 255, 0, 1))
    drawing_layer.polygon([(width, 0), (width - 30, 0), (width - 30, height),
                           (width, height)],
                          fill=(0, 0, 255, 0),
                          outline=(0, 255, 0, 1))
    drawing_layer.polygon([(0, 0), (width, 0), (width, 30), (0, 30)],
                          fill=(0, 0, 255, 0),
                          outline=(0, 255, 0, 1))
    drawing_layer.polygon([(0, height), (width, height), (width, height - 30),
                           (0, height - 30)],
                          fill=(0, 0, 255, 0),
                          outline=(0, 255, 0, 1))

    # Make the new image, starting with all transparent
    result = PIL.Image.new('RGBA', original_image.size, (136, 39, 16, 255))
    result.paste(original_image, (0, 0), mask=border_mask)

    img = Image.open('ourlogo.png')
    logo_small = img.resize((85, 93))
    result.paste(logo_small, (width - 130, 40), mask=logo_small)

    return result
Example #17
0
 def _get_border_image(self, type_):
     if type_ not in self.Borders:
         raise ValueError(
             'Unknown border "{}". Available types: {}'.format(
                 type_, ', '.join(self.list_border_types())))
     border_dir = os.path.join(os.path.dirname(__file__), 'data',
                               'borders')
     match_file = self.Borders[type_]
     for fname in glob.glob(os.path.join(border_dir, 'border*')):
         if fname == match_file:
             img = PIL.open(fname)
             break
     else:
         raise RuntimeError(
             'Border image "{}" not found in dir "{}"'.format(
                 match_file, border_dir))
     return img
Example #18
0
def generateMaps(mapFileName, numMaps, start_state, goal_state):
    # Inputs:
    #       mapFileName - string of the file name (including local path)
    #       numMaps - number of maps to be generated
    #
    # Outputs:
    #       generatedMap_cell - cell array containing numMaps+1 maps
    #                           the first element contains the seed map
    #

    import PIL
    import matplotlib.plyplot as plt

    map_seed = PIL.open(mapFileName).convert('L')

    bridge_ind = numpy.where(map_seed != 0 & map_seed !=
                             1)  # locations in the map where a bridge exists
    bridge_probs = map_seed[bridge_ind]  # probability for those bridges
    N = bridge_ind.shape[0]  # Number of bridges

    # Holds the output for the generated bridges
    generatedMap_cell = []

    for i in range(0, numMaps):
        temp_map = map_seed
        rand_vals = np.rand(N, 1)  # generate a random value for each bridge
        bridge_vals = rand_vals < bridge_probs  # are the bridges open?
        temp_map[bridge_ind] = bridge_vals  # create the maps
        generatedMap_cell[i] = temp_map  # store the maps in the cell array

        #plot the maps for testing
        plt.figure(i)
        plt.imshow(scipy.misc.imresize(temp_map, 5, interp='nearest'))

    (N, M) = map_seed.shape
    (x, y) = numpy.meshgrid(numpy.arange(1, N + 1), numpy.arange(1, M + 1))

    map_struct['map_name'] = mapFileName
    map_struct['bridge_locations'] = np.array(
        [x(bridge_ind).T, y(bridge_ind).T])
    map_struct['bridge_probabilities'] = bridge_probs
    map_struct['seed_map'] = map_seed
    map_struct['map_samples'] = generatedMap_cell
    map_struct['start'] = start_state
    map_struct['goal'] = goal_state
Example #19
0
def register(request):
    # pass
    if request.method == "POST":
        user_name = request.POST.get('username', '')
        pass_word_1 = request.POST.get('password_1', '')
        pass_word_2 = request.POST.get('password_2', '')
        nick_name = request.POST.get('nickname', '')
        email = request.POST.get('email', '')
        avatar = request.FILES.get('avatar')
        if User.objects.filter(username=user_name):
            return render(request, 'blog/register.html', {'error': '用户已存在'})
        if (pass_word_1 != pass_word_2):
            return render(request, 'blog/register.html', {'error': '两次密码输入不一致'})
        user = User()

        # 将头像设置为圆形
        if avatar:
            user.avatar = 'media/' + user_name + '.png'
            img = Image.open(avatar)
            size = img.size
            r2 = min(size[0], size(1))
            if size[0] != size[1]:
                img = img.resize((r2, r2), Image.ANTIALIAS)
            r3 = int(r2 / 2)
            img_circle = Image.new('RGBA', (r3 * 2, r3 * 2), (255, 255, 255, 0))
            pima = img.load()
            pimb = img_circle.load()
            r = float(r2 / 2)
            for i in range(r2):
                for j in range(r2):
                    lx = abs(i - r)
                    ly = abs(j - r)
                    l = (pow(lx, 2) + pow(ly, 2)) ** 0.5
                    if l < r3:
                        pimb[i - (r - r3), j - (r - r3)] = pima[i, j]
            img_circle.save('static/media/' + user_name + '.png')
        user.username = user_name
        user.password = pass_word_1
        user.email = email
        user.nickname = nick_name
        user.save()
        return render(request, 'blog/index_unlogin.html')
    else:
        return render(request, 'blog/register.html')
def to_numpy(item):
    '''
    convert input to numpy array
    input type: image-file-name, PIL image, torch tensor, numpy array
    '''
    if 'str' in str(type(item)):  # read the image as numpy array
        item = np.array(Image.open(item))
    elif 'PIL' in str(type(item)):
        item = np.array(item)
    elif 'torch' in str(type(item)):
        item = item.numpy()
    elif 'imageio' in str(type(item)):
        item = np.array(item)
    elif 'numpy' in str(type(item)):
        pass
    else:  # unsupported type
        print('WTF:', str(type(item)))
        return None
    return item
Example #21
0
def generateMaps(mapFileName, numMaps, start_state, goal_state):
    # Inputs:
    #       mapFileName - string of the file name (including local path)
    #       numMaps - number of maps to be generated
    #
    # Outputs:
    #       generatedMap_cell - cell array containing numMaps+1 maps
    #                           the first element contains the seed map
    #

    import PIL 
    import matplotlib.plyplot as plt

    map_seed = PIL.open(mapFileName).convert('L')

    bridge_ind = numpy.where(map_seed != 0 & map_seed != 1)  # locations in the map where a bridge exists
    bridge_probs = map_seed[bridge_ind]                # probability for those bridges
    N = bridge_ind.shape[0]                             # Number of bridges

    # Holds the output for the generated bridges
    generatedMap_cell = []                

    for i in range(0,numMaps):
       temp_map = map_seed
       rand_vals = np.rand(N,1)   # generate a random value for each bridge
       bridge_vals = rand_vals < bridge_probs  # are the bridges open?
       temp_map[bridge_ind] = bridge_vals  # create the maps
       generatedMap_cell[i] = temp_map # store the maps in the cell array
       
       #plot the maps for testing
       plt.figure(i)
       plt.imshow(scipy.misc.imresize(temp_map,5, interp = 'nearest'))
       
    (N, M) = map_seed.shape
    (x, y) = numpy.meshgrid(numpy.arange(1,N+1), numpy.arange(1,M+1)) 

    map_struct['map_name'] = mapFileName
    map_struct['bridge_locations'] = np.array([x(bridge_ind).T, y(bridge_ind).T])
    map_struct['bridge_probabilities'] = bridge_probs
    map_struct['seed_map'] = map_seed
    map_struct['map_samples'] = generatedMap_cell
    map_struct['start'] = start_state
    map_struct['goal'] = goal_state
Example #22
0
def pdf2img(pdf_path):
    image_list = []
    try:
        doc = fitz.open(pdf_path)
        for page_index, page in enumerate(doc):
            trans = fitz.Matrix(2.0, 2.0).preRotate(0)
            pm = page.getPixmap(matrix=trans, alpha=False)  # 获得每一页的流对象
            getpngdata = pm.getImageData(output="png")
            # 解码为 np.uint8
            image_array = np.frombuffer(getpngdata, dtype=np.uint8)
            img = cv2.imdecode(image_array, cv2.IMREAD_ANYCOLOR)
            image_list.append(img)
    except:
        image_pdf = Image(filename=pdf_path, resolution=200)
        with image_pdf.convert('jpg') as conv:
            for img in conv.sequence:
                img_page = Image(image=img).make_blob('jpg')
                image = io.BytesIO(img_page)
                img = np.array(PI.open(image).convert('RGB'))
                image_list.append(img)
    return image_list
Example #23
0
def savePlotSequence(P,fileBase,stride=1,imgRatio=(5,7),title=None,titleFrames=20,lastFrames=30):
	'''Save sequence of plots, each plot corresponding to one line in history. It is especially meant to be used for :obj:`woo.utils.makeVideo`.

	:param stride: only consider every stride-th line of history (default creates one frame per each line)
	:param title: Create title frame, where lines of title are separated with newlines (``\\n``) and optional subtitle is separated from title by double newline. 
	:param int titleFrames: Create this number of frames with title (by repeating its filename), determines how long the title will stand in the movie.
	:param int lastFrames: Repeat the last frame this number of times, so that the movie does not end abruptly.
	:return: List of filenames with consecutive frames.
	'''
	data,imgData,plots=P.data,P.imgData,P.plots
	fig=createPlots(P,noShow=True,replace=True,subPlots=True,scatterSize=60,wider=True)[0]
	sqrtFigs=math.sqrt(len(plots))
	fig.set_size_inches(8*sqrtFigs,5*sqrtFigs) # better readable
	fig.subplots_adjust(left=.05,right=.95,bottom=.05,top=.95) # make it more compact
	if len(plots)==1 and plots[plots.keys()[0]]==None: # only pure snapshot is there
		fig.set_size_inches(5,5)
		fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
	#if not data.keys(): raise ValueError("plot.data is empty.")
	pltLen=max(len(data[data.keys()[0]]) if data else 0,len(imgData[imgData.keys()[0]]) if imgData else 0)
	if pltLen==0: raise ValueError("Both plot.data and plot.imgData are empty.")
	global current
	ret=[]
	print 'Saving %d plot frames, it can take a while...'%(pltLen)
	for i,n in enumerate(range(0,pltLen,stride)):
		current=n
		for l in P.currLineRefs: l.update()
		out=fileBase+'-%03d.png'%i
		fig.savefig(out)
		ret.append(out)
		sys.stderr.write('[%d]'%i)
	if len(ret)==0: raise RuntimeError("No images created?!")
	if title:
		import Image
		titleImgName=fileBase+'-title.png'
		createTitleFrame(titleImgName,Image.open(ret[-1]).size,title)
		ret=titleFrames*[titleImgName]+ret
	if lastFrames>1: ret+=(lastFrames-1)*[ret[-1]]
	return ret
Example #24
0
def savePlotSequence(P,fileBase,stride=1,imgRatio=(5,7),title=None,titleFrames=20,lastFrames=30):
    '''Save sequence of plots, each plot corresponding to one line in history. It is especially meant to be used for :obj:`woo.utils.makeVideo`.

    :param stride: only consider every stride-th line of history (default creates one frame per each line)
    :param title: Create title frame, where lines of title are separated with newlines (``\\n``) and optional subtitle is separated from title by double newline. 
    :param int titleFrames: Create this number of frames with title (by repeating its filename), determines how long the title will stand in the movie.
    :param int lastFrames: Repeat the last frame this number of times, so that the movie does not end abruptly.
    :return: List of filenames with consecutive frames.
    '''
    data,imgData,plots=P.data,P.imgData,P.plots
    fig=createPlots(P,noShow=True,replace=True,subPlots=True,scatterSize=60,wider=True)[0]
    sqrtFigs=math.sqrt(len(plots))
    fig.set_size_inches(8*sqrtFigs,5*sqrtFigs) # better readable
    fig.subplots_adjust(left=.05,right=.95,bottom=.05,top=.95) # make it more compact
    if len(plots)==1 and plots[list(plots.keys())[0]]==None: # only pure snapshot is there
        fig.set_size_inches(5,5)
        fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
    #if not data.keys(): raise ValueError("plot.data is empty.")
    pltLen=max(len(data[list(data.keys())[0]]) if data else 0,len(imgData[list(imgData.keys())[0]]) if imgData else 0)
    if pltLen==0: raise ValueError("Both plot.data and plot.imgData are empty.")
    global current
    ret=[]
    print('Saving %d plot frames, it can take a while...'%(pltLen))
    for i,n in enumerate(range(0,pltLen,stride)):
        current=n
        for l in P.currLineRefs: l.update()
        out=fileBase+'-%03d.png'%i
        fig.savefig(out)
        ret.append(out)
        sys.stderr.write('[%d]'%i)
    if len(ret)==0: raise RuntimeError("No images created?!")
    if title:
        import Image
        titleImgName=fileBase+'-title.png'
        createTitleFrame(titleImgName,Image.open(ret[-1]).size,title)
        ret=titleFrames*[titleImgName]+ret
    if lastFrames>1: ret+=(lastFrames-1)*[ret[-1]]
    return ret
Example #25
0
def user_color(original, new):
    '''allows user to change border colors from set options'''
    img = Image.open(original)  #opens original image
    #adds border to original
    color = raw_input('What color would you like the border to be?(Prompt \
will appear until all images are have a chosen color.): \n')
    time.sleep(1)
    thic = raw_input('What width would you like the border to be?(Prompt \
will appear until all images are have a chosen width.): \n')
    try:
        img_with_border = ImageOps.expand(img,
                                          border=int(thic),
                                          fill=str(color))
    except ValueError:
        img_with_border = ImageOps.expand(img, border=30, fill=str("blue"))
    try:
        img_with_border = ImageOps.expand(img,
                                          border=int(thic),
                                          fill=str(color))
    except TypeError:
        img_with_border = ImageOps.expand(img, border=30, fill=str("blue"))

    return img_with_border
Example #26
0
def rescale(data, width, height, force=True):
    """Rescale the given image, optionally cropping it to make sure the result image has the specified width and height."""

    max_width = width
    max_height = height

    input_file = StringIO(data)
    img = pil.open(input_file)
    if not force:
        img.thumbnail((max_width, max_height), pil.ANTIALIAS)
    else:
        src_width, src_height = img.size
        src_ratio = float(src_width) / float(src_height)
        dst_width, dst_height = max_width, max_height
        dst_ratio = float(dst_width) / float(dst_height)
        
        if dst_ratio < src_ratio:
            crop_height = src_height
            crop_width = crop_height * dst_ratio
            x_offset = float(src_width - crop_width) / 2
            y_offset = 0
        else:
            crop_width = src_width
            crop_height = crop_width / dst_ratio
            x_offset = 0
            y_offset = float(src_height - crop_height) / 3
        img = img.crop((x_offset, y_offset, x_offset+int(crop_width), y_offset+int(crop_height)))
        img = img.resize((dst_width, dst_height), pil.ANTIALIAS)
        
    tmp = StringIO()
    img.save(tmp, 'JPEG')
    tmp.seek(0)
    output_data = tmp.getvalue()
    input_file.close()
    tmp.close()
    
    return output_data
Example #27
0
import PIL as IMAGE

file_src = 'img processing/imgs/fire/T0t0.jpg'  #需要压缩的图片地址
img_src = 'img processing/imgs/fire/yasuo.jpg'  #压缩后的图片地址
img = IMAGE.open(file_src)
w, h = img.size
w, h = round(w * 0.2), round(h * 0.2)  # 去掉浮点,防报错

img = img.resize((w, h), IMAGE.ANTIALIAS)
img.save(img_src, optimize=True, quality=85)  #	 质量为85效果最好
Example #28
0
def border_one(original_image, percent_of_side=.3):
    """ Rounds the corner of a PIL.Image
        original_image must be a PIL.Image
        Returns a new PIL.Image with rounded corners, where
        0 < percent_of_side < 1 is the corner radius as a portion of the shorter 
        dimension of original_image
    """
    #set the radius of the rounded corners
    width, height = original_image.size

    ###
    #create a mask
    ###

    #start with transparent mask
    border_mask = PIL.Image.new('RGBA', (width, height), (127, 0, 127, 0))
    drawing_layer = PIL.ImageDraw.Draw(border_mask)

    # Overwrite the RGBA values with A=255.
    # The 127 for RGB values was used merely for visualizing the mask

    # Draw two rectangles to fill interior with opaqueness
    if width >= 300 or height >= 300:
        drawing_layer.polygon([(0, 0), (width, 0), (width, height),
                               (0, height)],
                              fill=(127, 0, 127, 170))

        drawing_layer.polygon([(0, 0), (30, 0), (30, height), (0, height)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))
        drawing_layer.polygon([(width, 0), (width - 30, 0),
                               (width - 30, height), (width, height)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))
        drawing_layer.polygon([(0, 0), (width, 0), (width, 30), (0, 30)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))
        drawing_layer.polygon([(0, height), (width, height),
                               (width, height - 30), (0, height - 30)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))

        # Make the new image, starting with all transparent
        result = PIL.Image.new('RGBA', original_image.size, (136, 39, 16, 255))
        result.paste(original_image, (0, 0), mask=border_mask)

        img = Image.open('ourlogo_test.png')
        logo_small = img.resize((85, 93))
        result.paste(logo_small, (width - 130, 40), mask=logo_small)

        return result

    elif width <= 300 and height <= 300:

        original_image.size = 500, 500

        drawing_layer.polygon([(0, 0), (width, 0), (width, height),
                               (0, height)],
                              fill=(127, 0, 127, 170))

        drawing_layer.polygon([(0, 0), (20, 0), (20, height), (0, height)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))
        drawing_layer.polygon([(width, 0), (width - 20, 0),
                               (width - 20, height), (width, height)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))
        drawing_layer.polygon([(0, 0), (width, 0), (width, 20), (0, 20)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))
        drawing_layer.polygon([(0, height), (width, height),
                               (width, height - 30), (0, height - 30)],
                              fill=(0, 0, 255, 0),
                              outline=(0, 255, 0, 1))

        # Make the new image, starting with all transparent
        result = PIL.Image.new('RGBA', original_image.size, (136, 39, 16, 255))
        result.paste(original_image, (0, 0), mask=border_mask)

        img = Image.open('ourlogo_test.png')
        logo_small = img.resize((10, 23))
        result.paste(logo_small, (width - 130, 40), mask=logo_small)

        return result
Example #29
0
 def update(self):
     if isinstance(self.line,matplotlib.image.AxesImage):
         # image name
         try:
             if len(self.xdata)==0 and self.dataName: self.xdata=self.imgData[self.dataName]  # empty list reference an empty singleton, not the list we want; adjust here
             import Image
             if self.xdata[current]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
             else: img=Image.open(self.xdata[current])
             self.line.set_data(img)
         except IndexError: pass
     else:
         # regular data
         import numpy
         # current==-1 avoids copy slicing data in the else part
         if current==None or current==-1 or afterCurrentAlpha==1:
             self.line.set_xdata(self.xdata); self.line.set_ydata(self.ydata)
             self.line2.set_xdata([]); self.line2.set_ydata([])
         else:
             try: # try if we can extend the first part by one so that lines are connected
                 self.xdata[:current+1]; preCurrEnd=current+1
             except IndexError: preCurrEnd=current
             preCurrEnd=current+(1 if len(self.xdata)>current else 0)
             self.line.set_xdata(self.xdata[:preCurrEnd]); self.line.set_ydata(self.ydata[:preCurrEnd])
             self.line2.set_xdata(self.xdata[current:]); self.line2.set_ydata(self.ydata[current:])
         try:
             x,y=self.xdata[current],self.ydata[current]
         except IndexError: x,y=0,0
         # this could be written in a nicer way, very likely
         try:
             pt=numpy.ndarray((2,),buffer=numpy.array([float(x),float(y)]))
             if self.scatter:
                 self.scatter.set_offsets(pt)
                 # change rotation of the marker (possibly incorrect)
                 try:
                     dx,dy=self.xdata[current]-self.xdata[current-1],self.ydata[current]-self.ydata[current-1]
                     # smoothing from last n values, if possible
                     # FIXME: does not show arrow at all if less than window values
                     #try:
                     #    window=10
                     #    dx,dy=[numpy.average(numpy.diff(dta[current-window:current])) for dta in self.xdata,self.ydata]
                     #except IndexError: pass
                     # there must be an easier way to find on-screen derivative angle, ask on the matplotlib mailing list
                     # XXX: this can be siplified once we drop support for matplotlib < 1.5
                     # XXX: and is here to avoid MatplotlibDeprecationWarning for newer versions
                     axes=_my_get_axes(self.line)
                     p=axes.patch; xx,yy=p.get_verts()[:,0],p.get_verts()[:,1]; size=max(xx)-min(xx),max(yy)-min(yy)
                     aspect=(size[1]/size[0])*(1./axes.get_data_ratio())
                     if dx==0: angle=math.pi
                     angle=math.atan(aspect*dy/dx)
                     if dx<0: angle-=math.pi
                     self.scatter.set_transform(matplotlib.transforms.Affine2D().rotate(angle))
                 except IndexError: pass
             if self.annotation:
                 if math.isnan(x) or math.isnan(y):
                     if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y)
                     else: self.annotation.xytext=(0,0)
                     self.annotation.set_text('') # make invisible, place anywhere
                 else:
                     #
                     if hasattr(self.annotation,'xyann'): self.annotation.xyann=(x,y) # newer MPL versions (>=1.4)
                     else: self.annotation.xyann=(x,y)
                     self.annotation.set_text(self.annotation.annotateFmt.format(xy=(float(x),float(y))))
         except TypeError: pass # this happens at i386 with empty data, saying TypeError: buffer is too small for requested array
Example #30
0
def createPlots(P,subPlots=True,noShow=False,replace=True,scatterSize=60,wider=False):
    '''Create plots based on current data;

    :param subPlots: show all plots in one figure as subplots; otherwise, create multiple figures
    :param noShow: use headless backend for plots, and do not show plots on the screen
    :param replace: do not close existing figures, and do not update P.currLineRefs
    '''
    import logging
    data,imgData,plots,labels,xylabels,legendLoc,axesWd,annotateFmt=P.data,P.imgData,P.plots,P.labels,P.xylabels,P.legendLoc,P.axesWd,P.annotateFmt
    if replace:
        if P.currLineRefs:
            logging.info('Closing existing figures')
            ff=set([_my_get_axes(l.line).get_figure() for l in P.currLineRefs]) # get all current figures
            for f in ff: pylab.close(f) # close those
        P.currLineRefs=[]
    figs=[]
    if len(plots)==0: return # nothing to plot
    if subPlots:
        # compute number of rows and colums for plots we have
        subCols=int(round(math.sqrt(len(plots)))); subRows=int(math.ceil(len(plots)*1./subCols))
        if wider: subRows,subCols=subCols,subRows
    # create a new figure; called once with subPlots, for each subplot without subPlots
    def _newFig():
        ## pylab API        
        if not noShow: return pylab.figure() # this will go onto the screen; the pylab call sets up the windows as well
        else: # with noShow
            fig=matplotlib.figure.Figure()
            canvas=_HeadlessFigureCanvas(fig) # 
            return fig
    if subPlots: figs=[_newFig()]
    for nPlot,p in enumerate(plots.keys()):
        pStrip=p.strip().split('=',1)[0]
        if not subPlots:
            figs.append(_newFig())
            axes=figs[-1].add_subplot(1,1,1)
        else: axes=figs[-1].add_subplot(subRows,subCols,nPlot+1) # nPlot is 1-based in mpl, for matlab comatibility
        axes.grid(True)
        if plots[p]==None: # image plot
            if not pStrip in list(imgData.keys()): imgData[pStrip]=[]
            # fake (empty) image if no data yet
            import Image
            if len(imgData[pStrip])==0 or imgData[pStrip][-1]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
            else: img=Image.open(imgData[pStrip][-1])
            img=axes.imshow(img,origin='upper')
            if replace: P.currLineRefs.append(LineRef(line=img,scatter=None,annotation=None,line2=None,xdata=imgData[pStrip],ydata=None,imgData=imgData,dataName=pStrip))
            axes.set_axis_off()
            continue
        plots_p=[addPointTypeSpecifier(o) for o in tuplifyYAxis(plots[p])]
        plots_p_y1,plots_p_y2=[],[]; y1=True
        missing=set() # missing data columns
        if pStrip not in list(data.keys()): missing.add(pStrip if isinstance(pStrip,str) else pStrip.decode('utf-8','ignore'))
        for d in plots_p:
            d0=d[0]
            if d0==None:
                y1=False; continue
            if not isinstance(d0,(past.builtins.str,str)): raise ValueError('Plots specifiers must be strings (not %s)'%(type(d[0]).__name__))
            if '=' in d0: d0=d0.split('=',1)[0]
            if y1: plots_p_y1.append((d0,d[1]))
            else: plots_p_y2.append((d0,d[1]))
            try:
                if (
                    d0 not in list(data.keys())
                    # and not callable(d[0])
                    and not (isinstance(d0,str) and (d0.startswith('**') or d0.startswith('*'))) # hack for callable as strings
                    # and not hasattr(d[0],'keys')
                ):
                    missing.add(d0)
            except UnicodeEncodeError:
                import warnings
                warnings.error('UnicodeDecodeError when processing data set '+repr(d[0]))
        if missing:
            if len(list(data.keys()))==0 or len(data[list(data.keys())[0]])==0: # no data at all yet, do not add garbage NaNs
                for m in missing: data[m]=[]
            else:
                addDataColumns(data,missing)
                try:
                    print('Missing columns in Scene.plot.data, added NaNs:',', '.join([m for m in missing]))
                except UnicodeDecodeError:
                    warnings.warn('UnicodeDecodeError reporting missing data columns -- harmless, just wondering...')
        def createLines(pStrip,ySpecs,axes,isY1=True,y2Exists=False):
            '''Create data lines from specifications; this code is common for y1 and y2 axes;
            it handles y-data specified as callables/dicts passed as string (starting with '*'/'**'), which might create additional lines when updated with liveUpdate.
            '''
            # save the original specifications; they will be smuggled into the axes object
            # the live updated will run yNameFuncs to see if there are new lines to be added
            # and will add them if necessary
            yNameFuncs=set()
            yNames=set()
            ySpecs2=[]
            for ys in ySpecs:
                if not isinstance(ys[0],(past.builtins.str,str)): raise ValueError('Plot specifications must be strings (not a %s).'%type(ys[0]))
                if ys[0].startswith('**') or ys[0].startswith('*'):
                    evEx=eval(ys[0][(2 if ys[0].startswith('**') else 1):],{'S':P.scene})
                    yNameFuncs.add(evEx)  # add callable or dictionary
                    # XXX: what is ys[1]? Previously, there was no line specifier there for dicts at least
                    # print evEx,type(evEx), evEx.__iter__(),type(evEx.__iter__())
                    ySpecs2+=[(ret,ys[1]) for ret in evEx] # traverse list or dict keys
                else: ySpecs2.append(ys)
            if len(ySpecs2)==0:
                print('woo.plot: creating fake plot, since there are no y-data yet')
                line,=axes.plot([nan],[nan])
                line2,=axes.plot([nan],[nan])
                if replace: P.currLineRefs.append(LineRef(line=line,scatter=None,annotation=None,line2=line2,xdata=[nan],ydata=[nan]))
            # set different color series for y1 and y2 so that they are recognizable
            if 'axes.color_cycle' in matplotlib.rcParams: matplotlib.rcParams['axes.color_cycle']='b,g,r,c,m,y,k' if not isY1 else 'm,y,k,b,g,r,c'
            for d in ySpecs2:
                yNames.add(d)
                # should have been handled above already
                #if pStrip not in data:
                #    print 'Missing column %s in Scene.plot.data, added NaN.'%pString
                #    addDataColumns(data,[pStrip])
                if d[0] not in data:
                    print('Missing column %s in Scene.plot.data, added NaN.'%d[0])
                    addDataColumns(data,[d[0]])
                line,=axes.plot(data[pStrip],data[d[0]],d[1],label=xlateLabel(d[0],P.labels),**lineKw)
                lineKwWithoutAlpha=dict([(k,v) for k,v in list(lineKw.items()) if k!='alpha'])
                line2,=axes.plot([],[],d[1],color=line.get_color(),alpha=afterCurrentAlpha,**lineKwWithoutAlpha)
                # use (0,0) if there are no data yet
                scatterPt=[0,0] if len(data[pStrip])==0 else (data[pStrip][current],data[d[0]][current])
                scatterPtPos=[scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0]
                # if current value is NaN, use zero instead
                scatter=axes.scatter(scatterPtPos[0],scatterPtPos[1],s=scatterSize,color=line.get_color(),**scatterMarkerKw)
                if annotateFmt:
                    if math.isnan(scatterPtPos[0]) or math.isnan(scatterPtPos[1]): text=''
                    else: text=annotateFmt.format(xy=scatterPt)
                    annotation=axes.annotate(text,xy=scatterPtPos,color=line.get_color(),**annotateKw)
                    annotation.annotateFmt=annotateFmt
                else: annotation=None
                if replace: P.currLineRefs.append(LineRef(line=line,scatter=scatter,annotation=annotation,line2=line2,xdata=data[pStrip],ydata=data[d[0]]))
            axes=_my_get_axes(line)
            labelLoc=(legendLoc[0 if isY1 else 1] if y2Exists>0 else 'best')
            l=axes.legend(loc=labelLoc)
            if l:
                l.get_frame().set_alpha(legendAlpha)
                if hasattr(l,'draggable'): l.draggable(True)
            if scientific:
                axes.ticklabel_format(style='sci',scilimits=(0,0),axis='both')
                # fixes scientific exponent placement for y2: https://sourceforge.net/mailarchive/forum.php?thread_name=20101223174750.GD28779%40ykcyc&forum_name=matplotlib-users
                if not isY1: axes.yaxis.set_offset_position('right')
            if isY1:
                axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if p not in xylabels or not xylabels[p][1] else xylabels[p][1])
                axes.set_xlabel(xlateLabel(pStrip,P.labels) if (p not in xylabels or not xylabels[p][0]) else xylabels[p][0])
            else:
                axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if (p not in xylabels or len(xylabels[p])<3 or not xylabels[p][2]) else xylabels[p][2])
            # if there are callable/dict ySpecs, save them inside the axes object, so that the live updater can use those
            if yNameFuncs:
                axes.wooYNames,axes.wooYFuncs,axes.wooXName,axes.wooLabelLoc=yNames,yNameFuncs,pStrip,labelLoc # prepend woo to avoid clashes
            if 0:
                # fix missing 'show' method; this has been fixed in matplotlib already, but we need to backport that
                # see https://github.com/matplotlib/matplotlib/commit/15fd0ae587a57cb1d7b69546eb359085315148c8
                # don't do that for headless backend, error there is fine
                fig=axes.get_figure()
                if not hasattr(fig,'show'):
                    mgr=getattr(fig.canvas,'manager')
                    if mgr: fig.show=lambda *args: mgr.window.show()
        createLines(pStrip,plots_p_y1,axes=axes,isY1=True,y2Exists=len(plots_p_y2)>0)
        if axesWd>0:
            axes.axhline(linewidth=axesWd,color='k')
            axes.axvline(linewidth=axesWd,color='k')
        # create y2 lines, if any
        if len(plots_p_y2)>0:
            axes=axes.twinx() # create the y2 axis
            createLines(pStrip,plots_p_y2,axes,isY1=False,y2Exists=True)
        ### scene is not directly accessible from here, do it like this:
        S=woo.master.scene
        if S.plot==P:
            if 'title' in S.tags: axes.set_title(S.tags['title'])
    return figs
Example #31
0
    """
    ha, wa = imga.shape[:2]
    hb, wb = imgb.shape[:2]
    max_height = np.max([ha, hb])
    total_width = wa + wb
    new_img = np.zeros(shape=(max_height, total_width, 3))
    new_img[:ha, :wa] = imga
    new_img[:hb, wa:wa + wb] = imgb
    return new_img


def concat_n_images(image_path_list):
    """
    Combines N color images from a list of image paths.
    """
    output = None
    for i, img_path in enumerate(image_path_list):
        img = plt.imread(img_path)[:, :, :3]
        if i == 0:
            output = img
        else:
            output = concat_images(output, img)
    return output


for i in glob.glob('D:/GitHub/GitTesis/RAW DATA/*.img'):
    fopen = PIL.open(i)
    output = concat_n_images(fopen)

    plt.imshow(output)
    plt.show()
Example #32
0
            k[int(gt[i][1]), int(gt[i][0])] = 1

    # generate density map
    k = gaussian_filter_density(k)

    # File path to save density map
    file_path = img_path.replace('.jpg', '.h5').replace('images', 'ground')

    with h5py.File(file_path, 'w') as hf:
        hf['density'] = k

# In[10]:

file_path = img_paths[22].replace('.jpg', '.h5').replace('images', 'ground')
print(file_path)

# In[12]:

#Sample Ground Truth
gt_file = h5py.File(file_path, 'r')
groundtruth = np.asarray(gt_file['density'])
plt.imshow(groundtruth, cmap=CM.jet)
print("Sum = ", np.sum(groundtruth))

# In[13]:

# Image corresponding to the ground truth
img = Image.open(file_path.replace('.h5', '.jpg').replace('ground', 'images'))
plt.imshow(img)
print(file_path.replace('.h5', '.jpg').replace('ground', 'images'))
Example #33
0
def createPlots(P,subPlots=True,noShow=False,replace=True,scatterSize=60,wider=False):
	'''Create plots based on current data;

	:param subPlots: show all plots in one figure as subplots; otherwise, create multiple figures
	:param noShow: use headless backend for plots, and do not show plots on the screen
	:param replace: do not close existing figures, and do not update P.currLineRefs
	'''
	import logging
	data,imgData,plots,labels,xylabels,legendLoc,axesWd,annotateFmt=P.data,P.imgData,P.plots,P.labels,P.xylabels,P.legendLoc,P.axesWd,P.annotateFmt
	if replace:
		if P.currLineRefs:
			logging.info('Closing existing figures')
			ff=set([l.line.get_axes().get_figure() for l in P.currLineRefs]) # get all current figures
			for f in ff: pylab.close(f) # close those
		P.currLineRefs=[]
	figs=[]
	if len(plots)==0: return # nothing to plot
	if subPlots:
		# compute number of rows and colums for plots we have
		subCols=int(round(math.sqrt(len(plots)))); subRows=int(math.ceil(len(plots)*1./subCols))
		if wider: subRows,subCols=subCols,subRows
	# create a new figure; called once with subPlots, for each subplot without subPlots
	def _newFig():
		## pylab API		
		if not noShow: return pylab.figure() # this will go onto the screen; the pylab call sets up the windows as well
		else: # with noShow
			fig=matplotlib.figure.Figure()
			canvas=_HeadlessFigureCanvas(fig) # 
			return fig
	if subPlots: figs=[_newFig()]
	for nPlot,p in enumerate(plots.keys()):
		pStrip=p.strip().split('=',1)[0]
		if not subPlots:
			figs.append(_newFig())
			axes=figs[-1].add_subplot(1,1,1)
		else: axes=figs[-1].add_subplot(subRows,subCols,nPlot+1) # nPlot is 1-based in mpl, for matlab comatibility
		axes.grid(True)
		if plots[p]==None: # image plot
			if not pStrip in imgData.keys(): imgData[pStrip]=[]
			# fake (empty) image if no data yet
			import Image
			if len(imgData[pStrip])==0 or imgData[pStrip][-1]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
			else: img=Image.open(imgData[pStrip][-1])
			img=axes.imshow(img,origin='upper')
			if replace: P.currLineRefs.append(LineRef(line=img,scatter=None,annotation=None,line2=None,xdata=imgData[pStrip],ydata=None,imgData=imgData,dataName=pStrip))
			axes.set_axis_off()
			continue
		plots_p=[addPointTypeSpecifier(o) for o in tuplifyYAxis(plots[p])]
		plots_p_y1,plots_p_y2=[],[]; y1=True
		missing=set() # missing data columns
		if pStrip not in data.keys(): missing.add(pStrip.decode('utf-8','ignore'))
		for d in plots_p:
			if d[0]==None:
				y1=False; continue
			if not isinstance(d[0],(str,unicode)): raise ValueError('Plots specifiers must be strings (not %s)'%(type(d[0]).__name__))
			if y1: plots_p_y1.append(d)
			else: plots_p_y2.append(d)
			try:
				if (
					d[0] not in data.keys()
					# and not callable(d[0])
					and not (isinstance(d[0],(str,unicode)) and (d[0].startswith('**') or d[0].startswith('*'))) # hack for callable as strings
					# and not hasattr(d[0],'keys')
				):
					missing.add(d[0])
			except UnicodeEncodeError:
				import warnings
				warnings.error('UnicodeDecodeError when processing data set '+repr(d[0]))
		if missing:
			if len(data.keys())==0 or len(data[data.keys()[0]])==0: # no data at all yet, do not add garbage NaNs
				for m in missing: data[m]=[]
			else:
				addDataColumns(data,missing)
				try:
					print 'Missing columns in Scene.plot.data, added NaNs:',', '.join([m.encode('utf-8') for m in missing])
				except UnicodeDecodeError:
					warnings.warn('UnicodeDecodeError reporting missing data columns -- harmless, just wondering...')
		def createLines(pStrip,ySpecs,axes,isY1=True,y2Exists=False):
			'''Create data lines from specifications; this code is common for y1 and y2 axes;
			it handles y-data specified as callables/dicts passed as string (starting with '*'/'**'), which might create additional lines when updated with liveUpdate.
			'''
			# save the original specifications; they will be smuggled into the axes object
			# the live updated will run yNameFuncs to see if there are new lines to be added
			# and will add them if necessary
			yNameFuncs=set()
			yNames=set()
			ySpecs2=[]
			for ys in ySpecs:
				if not isinstance(ys[0],(str,unicode)): raise ValueError('Plot specifications must be strings (not a %s).'%type(ys[0]))
				if ys[0].startswith('**') or ys[0].startswith('*'):
					evEx=eval(ys[0][(2 if ys[0].startswith('**') else 1):],{'S':P.scene})
					yNameFuncs.add(evEx)  # add callable or dictionary
					# XXX: what is ys[1]? Previously, there was no line specifier there for dicts at least
					# print evEx,type(evEx), evEx.__iter__(),type(evEx.__iter__())
					ySpecs2+=[(ret,ys[1]) for ret in evEx] # traverse list or dict keys
				else: ySpecs2.append(ys)
			if len(ySpecs2)==0:
				print 'woo.plot: creating fake plot, since there are no y-data yet'
				line,=axes.plot([nan],[nan])
				line2,=axes.plot([nan],[nan])
				if replace: P.currLineRefs.append(LineRef(line=line,scatter=None,annotation=None,line2=line2,xdata=[nan],ydata=[nan]))
			# set different color series for y1 and y2 so that they are recognizable
			if matplotlib.rcParams.has_key('axes.color_cycle'): matplotlib.rcParams['axes.color_cycle']='b,g,r,c,m,y,k' if not isY1 else 'm,y,k,b,g,r,c'
			for d in ySpecs2:
				yNames.add(d)
				# should have been handled above already
				#if pStrip not in data:
				#	print 'Missing column %s in Scene.plot.data, added NaN.'%pString
				#	addDataColumns(data,[pStrip])
				if d[0] not in data:
					print 'Missing column %s in Scene.plot.data, added NaN.'%d[0]
					addDataColumns(data,[d[0]])
				line,=axes.plot(data[pStrip],data[d[0]],d[1],label=xlateLabel(d[0],P.labels),**lineKw)
				lineKwWithoutAlpha=dict([(k,v) for k,v in lineKw.items() if k!='alpha'])
				line2,=axes.plot([],[],d[1],color=line.get_color(),alpha=afterCurrentAlpha,**lineKwWithoutAlpha)
				# use (0,0) if there are no data yet
				scatterPt=[0,0] if len(data[pStrip])==0 else (data[pStrip][current],data[d[0]][current])
				scatterPtPos=[scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0]
				# if current value is NaN, use zero instead
				scatter=axes.scatter(scatterPtPos[0],scatterPtPos[1],s=scatterSize,color=line.get_color(),**scatterMarkerKw)
				if annotateFmt:
					if math.isnan(scatterPtPos[0]) or math.isnan(scatterPtPos[1]): text=''
					else: text=annotateFmt.format(xy=scatterPt)
					annotation=axes.annotate(text,xy=scatterPtPos,color=line.get_color(),**annotateKw)
					annotation.annotateFmt=annotateFmt
				else: annotation=None
				if replace: P.currLineRefs.append(LineRef(line=line,scatter=scatter,annotation=annotation,line2=line2,xdata=data[pStrip],ydata=data[d[0]]))
			axes=line.get_axes()
			labelLoc=(legendLoc[0 if isY1 else 1] if y2Exists>0 else 'best')
			l=axes.legend(loc=labelLoc)
			if l:
				l.get_frame().set_alpha(legendAlpha)
				if hasattr(l,'draggable'): l.draggable(True)
			if scientific:
				axes.ticklabel_format(style='sci',scilimits=(0,0),axis='both')
				# fixes scientific exponent placement for y2: https://sourceforge.net/mailarchive/forum.php?thread_name=20101223174750.GD28779%40ykcyc&forum_name=matplotlib-users
				if not isY1: axes.yaxis.set_offset_position('right')
			if isY1:
				axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if p not in xylabels or not xylabels[p][1] else xylabels[p][1])
				axes.set_xlabel(xlateLabel(pStrip,P.labels) if (p not in xylabels or not xylabels[p][0]) else xylabels[p][0])
			else:
				axes.set_ylabel((', '.join([xlateLabel(_p[0],P.labels) for _p in ySpecs2])) if (p not in xylabels or len(xylabels[p])<3 or not xylabels[p][2]) else xylabels[p][2])
			# if there are callable/dict ySpecs, save them inside the axes object, so that the live updater can use those
			if yNameFuncs:
				axes.wooYNames,axes.wooYFuncs,axes.wooXName,axes.wooLabelLoc=yNames,yNameFuncs,pStrip,labelLoc # prepend woo to avoid clashes
			if 0:
				# fix missing 'show' method; this has been fixed in matplotlib already, but we need to backport that
				# see https://github.com/matplotlib/matplotlib/commit/15fd0ae587a57cb1d7b69546eb359085315148c8
				# don't do that for headless backend, error there is fine
				fig=axes.get_figure()
				if not hasattr(fig,'show'):
					mgr=getattr(fig.canvas,'manager')
					if mgr: fig.show=lambda *args: mgr.window.show()
		createLines(pStrip,plots_p_y1,axes=axes,isY1=True,y2Exists=len(plots_p_y2)>0)
		if axesWd>0:
			axes.axhline(linewidth=axesWd,color='k')
			axes.axvline(linewidth=axesWd,color='k')
		# create y2 lines, if any
		if len(plots_p_y2)>0:
			axes=axes.twinx() # create the y2 axis
			createLines(pStrip,plots_p_y2,axes,isY1=False,y2Exists=True)
		### scene is not directly accessible from here, do it like this:
		S=woo.master.scene
		if S.plot==P:
			if 'title' in S.tags: axes.set_title(S.tags['title'])
	return figs
Example #34
0
#Play Video
import cv2
import mediapipe as mp
import streamlit as st
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
y=["image"]

temp_status = len(os.listdir("image"))

#img = None

uploaded_file = st.file_uploader("Alternatively upload a file")
if uploaded_file is not None:
    img = Image.open(uploaded_file)
    img.save("image/hands.jpg")
    st.success("Uploaded.")

# For static images:
hands = mp_hands.Hands(
    static_image_mode=True,
    max_num_hands=2,
    min_detection_confidence=0.5)

st.write("Raw image") 

try:
    st.image(img, use_column_width=True)
except NameError:
    pass
Example #35
0
    image = Image.fromarray(255 * k)
    # image.show()

    # File path to save density map
    file_path = img_path.replace('.jpg', '.h5').replace('images', 'ground')

    with h5py.File(file_path, 'w') as hf:
        hf['density'] = k

# %%
path_test = "G:/pycharm/CSRnet-master/data/part_A_final/train_data/ground/IMG_107.h5"

# file_path = img_paths[-5].replace('.jpg','.h5').replace('images','ground')

file_path = path_test
print(file_path)

# %%
# Sample Ground Truth
gt_file = h5py.File(file_path, 'r')
groundtruth = np.asarray(gt_file['density'])
plt.imshow(groundtruth, cmap=CM.jet)
print("Sum = ", np.sum(groundtruth))
# %%
# Image corresponding to the ground truth
img = Image.open(file_path.replace('.h5',
                                   '.jpg').replace('ground',
                                                   'images')).convert('RGBA')
plt.imshow(img)
print(file_path.replace('.h5', '.jpg').replace('ground', 'images'))
import PIL as Image

pil_im = Image.open('C:\\Users\\Arsalan\\Desktop\\myprogress.PNG')

print(pil_im)