def numpyToWxImage(self, array):
		clip = self.contrasttool.getRange()
		normarray = array.astype(numpy.float32)
		if normarray.shape[0] == normarray.shape[1]  and normarray.shape[0] >= 4096:
			normarray = imagefun.bin2(normarray, 4)
		wximage = wx.EmptyImage(normarray.shape[1], normarray.shape[0])
		normarray = normarray.clip(min=clip[0], max=clip[1])
		normarray = (normarray - clip[0]) / (clip[1] - clip[0]) * 255.0
		if self.colormap is None:
			normarray = normarray.astype(numpy.uint8)
			h, w = normarray.shape[:2]
			imagedata = Image.fromstring("L", (w, h), normarray.tostring())
		else:
			valarray = normarray*6.0
			valarray = valarray.astype(numpy.uint16)
			remapColor = numpy.array(self.colormap)
			rgbarray = remapColor[valarray].astype(numpy.uint8)
			print rgbarray[:,:,0]
			h, w = normarray.shape[:2]
			r = Image.fromstring("L", (w, h), rgbarray[:,:,0].tostring())
			g = Image.fromstring("L", (w, h), rgbarray[:,:,1].tostring())
			b = Image.fromstring("L", (w, h), rgbarray[:,:,2].tostring())
			imagedata = Image.merge("RGB", (r,g,b))
		wximage.SetData(imagedata.convert('RGB').tostring())
		return wximage
def _arrayToImage(a):
        """
        Converts array object (numpy) to image object (PIL).
        """
        h, w = a.shape[:2]
        boolean = numpy.bool_
        int32 = numpy.int32
        uint32 = numpy.uint32
        float32 = numpy.float32
        float64 = numpy.float64

        if a.dtype==boolean or a.dtype==int32 or a.dtype==uint32 or a.dtype==float32 or a.dtype==float64:
                a = a.astype(numpy.uint8) # convert to 8-bit

        if len(a.shape)==3:
                if a.shape[2]==3:  # a.shape == (y, x, 3)
                        r = Image.fromstring("L", (w, h), a[:,:,0].tostring())
                        g = Image.fromstring("L", (w, h), a[:,:,1].tostring())
                        b = Image.fromstring("L", (w, h), a[:,:,2].tostring())
                        return Image.merge("RGB", (r,g,b))
                elif a.shape[2]==1:  # a.shape == (y, x, 1)
                        return Image.fromstring("L", (w, h), a.tostring())
        elif len(a.shape)==2:  # a.shape == (y, x)
                return Image.fromstring("L", (w, h), a.tostring())
        else:
                raise ValueError, "unsupported image mode"
Example #3
0
 def compress(image_format, size, data):
     from PIL import Image
     import cStringIO
     fake_file = cStringIO.StringIO()
     Image.fromstring(image_format, size, data).save(
         fake_file, 'jpeg', quality=quality)
     return fake_file.getvalue()
Example #4
0
    def DrawGLScene(self):
        """Main drawing function"""
        # Clear The Screen And The Depth Buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        self.drawHuman()

        # Export rendered images to file
        if not self.imageExported:
            self.imageExported = True

            print "[OGLDraw::DrawGLScene] : Color plane depths: "
            print '  R '+str(glGetIntegerv( GL_RED_BITS ))+' bits'
            print '  G '+str(glGetIntegerv( GL_GREEN_BITS ))+' bits'
            print '  B '+str(glGetIntegerv( GL_BLUE_BITS ))+' bits'
            print '  A '+str(glGetIntegerv( GL_ALPHA_BITS ))+' bits'

            # Read pixels back and store in image file (using imagemagick/PIL)
            data = glReadPixels(0,0, 640, 480, GL_RGBA, GL_UNSIGNED_BYTE)
            image = Image.fromstring("RGBA", (640, 480), data, "raw", "RGBA", 0, -1)

            alphaData = image.tostring("raw", "A")
            alphaImage = Image.fromstring("L", image.size, alphaData)
            alphaImage.show()
            alphaImage.save("depth.png")

            fullOpaque = Image.new("1", (640, 480), 1)
            image.putalpha(fullOpaque)
            image.show()
            image.save('labels.png', 'PNG')

        #  since this is double buffered, swap the buffers to display what just got drawn. 
        glutSwapBuffers()
Example #5
0
    def _get_rgbd_image(self):
        """
        Reads the colour and the depth buffer and returns numpy arrays
        """
        # read the colour buffer
        pixels = gl.glReadPixels(0, 0, self.width, self.height,
                                 gl.GL_RGBA, gl.GL_UNSIGNED_BYTE)
        # convert to PIL image
        image = Image.fromstring('RGBA', (self.width, self.height), pixels)
        image = image.transpose(Image.FLIP_TOP_BOTTOM)
        # convert to numpy array
        im = np.array(image.getdata(), np.uint8).reshape(self.height,
                                                         self.width, 4)
        # we have to get rid of the alpha channel to get the correct result
        im_res = np.copy(im[:, :, :3])
        # convert to float and divide by 255. to get values between 0 and 1
        im_res = im_res.astype(np.float32)/255.

        # now take care of the depth part
        depth_raw = gl.glReadPixels(0, 0, self.width, self.height,
                                    gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT)
        # convert to PIL image
        depth = Image.fromstring('F', (self.width, self.height), depth_raw)
        depth = depth.transpose(Image.FLIP_TOP_BOTTOM)
        # convert to numpy array
        d = np.array(depth.getdata(), np.float32).reshape(self.height,
                                                          self.width, 1)

        # linearize depth values
        d = 2. * d - 1.
        d = 2. * self.z_near * self.z_far / \
            (self.z_far + self.z_near - d * (self.z_far - self.z_near))
        return im_res, d
Example #6
0
def IPLImage2TkImage(iplimage):
    u'''IPLImageをTk用に変換'''
    assert iplimage.depth == 8 and iplimage.nChannels in [1, 3]
    if iplimage.nChannels == 3:
        image = Image.fromstring('RGB', cv.GetSize(iplimage), iplimage.tostring(), 'raw', 'BGR', iplimage.width * 3, 0)
    elif iplimage.nChannels == 1:
        image = Image.fromstring('L', cv.GetSize(iplimage), iplimage.tostring())
    return itk.PhotoImage(image)
Example #7
0
 def _save(self, fname):
     from PIL import Image
     self.__drawstuff()
     gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
     width = self.__windowsize[0]
     height = self.__windowsize[1]
     data = gl.glReadPixels(0, 0, width, height, gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
     Image.fromstring("RGB", (width, height), data).save(fname)
Example #8
0
def convertImageToPDF(_fileName, _swfslides, isDocin):
    print "convecting files to pdf..."
    pdfCanvas = canvas.Canvas("%s.pdf" % _fileName, pagesize=portrait(A4))
    # pdfCanvas.drawString(150,700,"Welcome to flash slides downloader");
    # pdfCanvas.drawString(180,680,"contact: [email protected]");
    # pdfCanvas.showPage()
    numberOfSlides = 1
    for iswf in _swfslides:
        doc = gfx.open("swf", iswf)
        print iswf
        if doc:
            if isDocin == False:
                for pagenr in range(1, doc.pages + 1):
                    page1 = doc.getPage(pagenr)
                    print "Page", pagenr, "has dimensions", page1.width, "x", page1.height
                    pdfCanvas.setPageSize((page1.width * 2, page1.height * 2))
                    imageName = "image-%s-%s.png" % (numberOfSlides, pagenr)
                    imgRGBBuf = page1.asImage(page1.width * 2, page1.height * 2)
                    im = Image.fromstring(
                        "RGB", (page1.width * 2, page1.height * 2), imgRGBBuf
                    )  # convert to PIL Object
                    # img = gfx.ImageList()
                    # 				img.setparameter("antialise", "4") # turn on antialisin
                    # img.setparameter("zoom", "100")
                    # img.startpage(page1.width,page1.height)
                    # 				page1.render(img)
                    # 				img.endpage()
                    # pageNumOfThisSwf+=1"thumbnail%s.png" % pagenr
                    # img.save(imageName)
                    # pdfCanvas.drawImage(imageName,0,0,width= page1.width,height= page1.height,mask='auto')
                    pdfCanvas.drawImage(
                        ImageReader(im), 0, 0, width=page1.width * 2, height=page1.height * 2, mask="auto"
                    )
                    pdfCanvas.showPage()
                    # os.remove(imageName) # delete temp image
            else:
                # damn docins bad header.
                page1 = doc.getPage(1)
                print "Page %d" % numberOfSlides, "has dimensions", page1.width, "x", page1.height
                pdfCanvas.setPageSize((page1.width * 2, page1.height * 2))
                imageName = "image-%s-%s.png" % (numberOfSlides, 1)
                imgRGBBuf = page1.asImage(page1.width * 2, page1.height * 2)
                im = Image.fromstring("RGB", (page1.width * 2, page1.height * 2), imgRGBBuf)  # convert to PIL Object
                # img = gfx.ImageList()
                # img.setparameter("antialise", "4") # turn on antialisin
                # img.setparameter("zoom", "100")
                # img.startpage(page1.width,page1.height)
                # page1.render(img)
                # img.endpage()
                # pageNumOfThisSwf+=1"thumbnail%s.png" % pagenr
                # img.save(imageName)
                # pdfCanvas.drawImage(imageName,0,0,width= page1.width,height= page1.height,mask='auto')
                pdfCanvas.drawImage(ImageReader(im), 0, 0, width=page1.width * 2, height=page1.height * 2, mask="auto")
                pdfCanvas.showPage()
                # os.remove(imageName) # delete temp image
        numberOfSlides += 1
        os.remove(iswf)  # delete temp swf
    pdfCanvas.save()
Example #9
0
def get_captcha_image(code):
    size_y = 32
    image_data = captchaimage.create_image(
        FONT_FILE, 28, size_y, code)
    file = cStringIO.StringIO()
    Image.fromstring(
        "L", (len(image_data) / size_y, size_y), image_data).save(
        file, "JPEG", quality = 30)
    return file.getvalue()
Example #10
0
 def __init__(self, img, info):
   self.buffer=img
   self.info = info
   if info.type() == "L":
     self.image = Image.fromstring("L", info.size(), img, "raw", "L")
   else:
     self.image = Image.fromstring(info.type(), info.size(), img, "raw", "BGR")
   self.fov = 0.
   self.asprct_ratio = 4.0/3.0
Example #11
0
 def getPILImage(self, buf, w1, h1, w2, h2, recv=False):
     if not recv:
         img = Image.fromstring('RGB', (w1,h1), buf, 'raw', 'BGR', 0, -1)
         img=img.resize((w2,h2))
         img=img.transpose(Image.FLIP_LEFT_RIGHT)
     else:
         img= Image.fromstring('RGB',(w1,h1), buf, 'raw')
         img=img.resize((w2,h2))
     return img
Example #12
0
def get_captcha_image(code):
    size_y = 32
    image_data = captchaimage.create_image(
        "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 28, size_y, code)
    file = cStringIO.StringIO()
    Image.fromstring(
        "L", (len(image_data) / size_y, size_y), image_data).save(
        file, "JPEG", quality = 30)
    return file.getvalue()
 def __processVideoFrame(self, frame):
   """ 
   Process the most recently read video frame (either from the live 
   camera or a video file) to prepare for passing into the network.
   First we ensure the image size matches the size that the network
   is expecting (we resize the image if needed).  Then if motion
   detection is enabled we compare the current video frame to the
   previous frame and only keep those pixels where changes have occurred.
   If the live camera is used we perform a mirror operation for a more
   intuitive look when using a front-facing webcam.
   @param frame: the most recently acquired OpenCV video frame image.
   """
   #if frame exactly matches network and motionDetect is off, then
   #just return a gray-scale version of the image to avoid extra resizes
   if frame.width==self._networkSize[0] and frame.height==self._networkSize[1]:
     if not self._motionDetect:
       cv.CvtColor(frame, self._inputImageNet, cv.CV_RGB2GRAY)
       return Image.fromstring('L', self._networkSize, 
                               self._inputImageNet.tostring(), 'raw','L',0,1)
   
   #if camera's frame size is incorrect, resize to what we need
   canvasSize = Layer.canvasSize
   if frame.width!=canvasSize[0] or frame.height!=canvasSize[1]:
     if self._frameImage==None:
       self._frameImage = cv.CreateImage(canvasSize, cv.IPL_DEPTH_8U, 3)
     cv.Resize(frame, self._frameImage)
   else: #size is already correct, use frame as-is
     self._frameImage = frame
   
   #convert camera image to gray-scale to perform motion analysis
   cv.CvtColor(self._frameImage, self._inputImage, cv.CV_RGB2GRAY)
   
   # perform motion detection and get the processed image frame
   # the new frame will either be None (no motion) or the motion box subset image
   rect = None
   if self._motionDetect:
     rect = self.processMotion()
   
   if rect!=None:
     mask0 = Image.fromstring('L', canvasSize, 
                              self._threshImage.tostring(), 'raw', 'L', 0, 1)
     xy = (rect[0], rect[1], rect[0]+rect[2], rect[1]+rect[3])
     
     #erase motionImage and paste only thresholded motion pixels on top
     draw = ImageDraw.Draw(self._motionImage)
     draw.rectangle((0,0,self._networkSize[0],self._networkSize[1]), fill="black")
     del draw
     
     imgMask = mask0.crop(xy)
     self._motionImage.paste(imgMask, xy)
     frameOut = self._motionImage
   else:
     frameOut = Image.fromstring('L', canvasSize, 
                                 self._inputImage.tostring(), 'raw', 'L', 0, 1)
   
   return frameOut.resize(self._networkSize)
Example #14
0
File: draw.py Project: gyver/p2pool
def get(tracker, best):
    d = pygame.Surface((400, 600), 32)
    if tracker.get_height(best) >= 100:
        t = time.time()
        start = tracker.get_nth_parent_hash(best, 100)
        d.fill((0, 0, 0))
        go(tracker.shares[start], tracker, t, d)
    f = StringIO.StringIO()
    Image.fromstring("RGB", d.get_size(), pygame.image.tostring(d, "RGB")).save(f, "png")
    return f.getvalue()
Example #15
0
def SaveToPng(result,name):
	print("Resizing result to be in range 0-255")
	result = (result.astype(numpy.float32)*(255.0/result.max())).astype(numpy.uint8)
	print("Done resizing. Now generating image array.")

	result = result.reshape((result.shape[1],result.shape[0]))
	print("Done generating image array. Writing image file.")

	Image.fromstring("L",(result.shape[1],result.shape[0]),result.tostring()).save(name+".png")
	print("Image file written.")
Example #16
0
    def updateCursor(self, x, y, width, height, image, mask):
        if self.factory.nocursor:
            return

        if not width or not height:
            self.cursor = None

        self.cursor = Image.fromstring('RGBX', (width, height), image)
        self.cmask = Image.fromstring('1', (width, height), mask)
        self.cfocus = x, y
        self.drawCursor()
Example #17
0
 def toImage(self):
     palette = ImagePalette.ImagePalette("RGB")
     palette.dirty = 1
     for i in range(256):
         k = (i*48)%256
         palette.palette[i] = [k, k, k]
     w = self.char.width*8
     h = self.char.height*8
     data = self.char.toString()
     if not w or not h:
         return Image.fromstring("P", (1, 1), "\x00")
     return Image.fromstring("P", (w, h), data)
Example #18
0
def preview(np, fmt, size, data):

    def chan(x):
        return Image.fromstring("L", size, (255 * x).astype(np.uint8))

    if fmt == gd2.L1:
        r = Image.fromstring("1", size, data)
    elif fmt == gd2.L8:
        r = Image.fromstring("L", size, data)
    else:
        d8 = np.array(data)
        a = np.ones(size[0] * size[1])
        (r, g, b) = (a, a, a)
        if fmt == gd2.ARGB4:
            d16 = np.array(array.array('H', data.tostring()))
            a = (15 & (d16 >> 12)) / 15.
            r = (15 & (d16 >> 8)) / 15.
            g = (15 & (d16 >> 4)) / 15.
            b = (15 & (d16 >> 0)) / 15.
        elif fmt == gd2.RGB565:
            d16 = np.array(array.array('H', data.tostring()))
            r = (31 & (d16 >> 11)) / 31.
            g = (63 & (d16 >> 5)) / 63.
            b = (31 & (d16 >> 0)) / 31.
        elif fmt == gd2.ARGB1555:
            d16 = np.array(array.array('H', data.tostring()))
            a = (1 & (d16 >> 15))
            r = (31 & (d16 >> 10)) / 31.
            g = (31 & (d16 >> 5)) / 31.
            b = (31 & (d16 >> 0)) / 31.
        elif fmt == gd2.ARGB2:
            a = (3 & (d8 >> 6)) / 3.
            r = (3 & (d8 >> 4)) / 3.
            g = (3 & (d8 >> 2)) / 3.
            b = (3 & (d8 >> 0)) / 3.
        elif fmt == gd2.RGB332:
            r = (7 & (d8 >> 5)) / 7.
            g = (7 & (d8 >> 2)) / 7.
            b = (3 & (d8 >> 0)) / 3.
        elif fmt == gd2.L4:
            hi = d8 >> 4
            lo = d8 & 15
            d4 = np.column_stack((hi, lo)).flatten()
            r = d4 / 15.
            g = r
            b = r
        o = Image.merge("RGB", [chan(c) for c in (r, g, b)])
        bg = Image.new("RGB", size, (128, 128, 128))
        r = Image.composite(o, bg, chan(a))

    r = r.resize((r.size[0] * 5, r.size[1] * 5), Image.NEAREST)
    return r
Example #19
0
def read_pcx(data):
    size,width,height = struct.unpack("<III",data[:12])
    if size == width*height:
        im = Image.fromstring('P', (width,height),data[12:12+width*height])
        palette = []
        for i in range(256):
            offset=12+width*height+i*3
            r,g,b = struct.unpack("<BBB",data[offset:offset+3])
            palette.extend((r,g,b))
        im.putpalette(palette)
        return im
    elif size == width*height*3:
        return Image.fromstring('RGB', (width,height),data[12:])
    else:
        return None
Example #20
0
	def extract_bmp(self, numbmp,width,height):
		if not self.bmp_dict.has_key(numbmp):
			return
		chunk=self.bmp_dict[numbmp]
		palflag = ord(chunk.data[0x36])
		[bmpsize] = struct.unpack('<L',chunk.data[42:46])
		[bmpstart] = struct.unpack('<L',chunk.data[50:54])
		
		numcol = (bmpstart - 82)/3
		if palflag == 5:
			numcol = 256
		bmpstart2 = numcol*4 + 54
		bmpstart2 = struct.pack('<L',bmpstart2)
		
		if palflag == 3:#CMYK image
			self.bmpbuf=chunk.data[bmpstart+40:]
			self.extracted_image = Image.fromstring('CMYK', (width, height), self.bmpbuf, 'raw', 'CMYK', 0, -1)
		elif palflag == 5:#Grayscale image
			self.bmpbuf=chunk.data[bmpstart+40:]
			bytes=math.ceil(width/2.0)*2
			self.extracted_image = Image.fromstring('L', (width, height), self.bmpbuf, 'raw', 'L', bytes, -1)
		elif palflag == 6: #Mono image
			bmpstart2 = numcol*4 + 66
			bmpstart2 = struct.pack('<L',bmpstart2)		
			self.bmpbuf = 'BM'+chunk.data[42:50]+bmpstart2[0:4]+'\x28\x00\x00\x00'
			self.bmpbuf += chunk.data[62:72]+chunk.data[74:78]
			self.bmpbuf += '\x00\x00'+chunk.data[82:90]+'\x00\x00\x00\x00'
			self.bmpbuf += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
			self.bmpbuf += chunk.data[bmpstart+40:]			
			self.extracted_image = Image.open(StringIO.StringIO(self.bmpbuf ))
			self.extracted_image.load()
			
#		elif palflag == 1: #RGB
#			print 'width, height', (width, height)
#			self.bmpbuf=chunk.data[bmpstart+40:]
#			self.extracted_image = Image.fromstring('RGB', (width, height), self.bmpbuf, 'raw', 'BGR', 0, -1)
		
		else:
			self.bmpbuf = 'BM'+chunk.data[42:50]+bmpstart2[0:4]+'\x28\x00\x00\x00'
			self.bmpbuf += chunk.data[62:72]+chunk.data[74:78]
			self.bmpbuf += '\x00\x00'+chunk.data[82:90]+'\x00\x00\x00\x00'
			if numcol > 1:
				self.bmpbuf = self.bmpbuf+'\x00\x01\x00\x00\x00\x00\x00\x00'
				for i in range (numcol):
					self.bmpbuf = self.bmpbuf+chunk.data[122+i*3:125+i*3]+'\x00'
			self.bmpbuf += chunk.data[bmpstart+40:]
			self.extracted_image = Image.open(StringIO.StringIO(self.bmpbuf ))
			self.extracted_image.load()
 def captureFromFile(self):
   """ 
   Capture a frame from the active video file and return it so it can
   then be passed into the Region for analysis.
   """
   #when playing files, cap playback at necessary FPS
   tsec = clock()
   if tsec-self._lastFrameTime < self._secPerFrame:
     return
   self._lastFrameTime = tsec
   
   frame = cv.QueryFrame(self._capture)
   if not frame: #if no more frames, stop stream
     self.stopRun()
     return
   
   #if video file's frame size incorrect, resize to what region expects
   if frame.width!=self._frame80.width or frame.height!=self._frame80.height:
     if self._fileImage==None:
       self._fileImage = cv.CreateImage(self._regionShape, cv.IPL_DEPTH_8U, 3)
     cv.Resize(frame, self._fileImage)
     frame = self._fileImage
   
   #convert file to gray-scale and build a PIL image from it
   cv.CvtColor(frame, self._frame80, cv.CV_RGB2GRAY)
   
   frameOut = Image.fromstring('L', (self._frame80.width, self._frame80.height), \
                               self._frame80.tostring(), 'raw', 'L', 0, 1)
   return frameOut
Example #22
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, coord, tile_scale):
        """
        """
        start_time = time()
        
        if self.mapnik is None:
            self.mapnik = get_mapnikMap(self.mapfile)
            logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile)
        
        #
        # Mapnik can behave strangely when run in threads, so place a lock on the instance.
        #
        if global_mapnik_lock.acquire():
            self.mapnik.width = width
            self.mapnik.height = height
            self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax))
            
            img = mapnik.Image(width, height)
            mapnik.render(self.mapnik, img)
            global_mapnik_lock.release()
        
        img = Image.fromstring('RGBA', (width, height), img.tostring())

        logging.error('Mapnik.renderArea: {"ts":%.0f,"mapfile":"%s","z":%d,"x":%d,"y":%d,"time":%f}', start_time, self.mapfile, coord.zoom, coord.column, coord.row, time() - start_time)
        logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %dx%d in %.3f from %s', width, height, time() - start_time, self.mapfile)
    
        return img
    def keyPressHandler(self, obj, event):
        '''
        Grabs the current framebuffer, coverts it to a JPEG, and sends it through the socket.
        '''
        if obj.GetKeySym() == 's':
            self.renwin.Render()
            self.w2i.Modified()
            self.w2i.Update()
            imageData = self.w2i.GetOutput()

            # Convert the GL framebuffer into a numpy array
            rawImage = VN.vtk_to_numpy(imageData.GetPointData().GetScalars())
            rawImageArray = numpy.array(rawImage.flatten(), numpy.uint8)

            # convert to a PIL image so we can compress as JPG and stream over a socket
            x = self.renwin.GetSize()[0]
            y = self.renwin.GetSize()[1]
            img = Image.fromstring('RGB',(x,y), rawImageArray, 'raw', 'RGB')

            # StringIO serves as a memory endpoint for the compressed JPEG
            output = StringIO()
            img.save(output, format="JPEG")
            
            # get a byte array of the jpg then send:
            # 1. size stamp 1+8 bytes
            # 2. image buffer
            # 3. end stamp
            buf = output.getvalue()
            datasize = str(len(buf))
            datasize = datasize.zfill(8)
            print 'Sending pixel stream of size: ' + datasize + ' bytes.'
            self.client.send('s' + datasize)
            self.client.send(buf)
            self.client.send('e')
Example #24
0
 def screenshot(self):
     image = pyglet.image.get_buffer_manager().get_color_buffer()
     if hasattr(self, '_hwnd') and not self.modifiers & key.MOD_CTRL:
         from ctypes import windll, cdll
         from PIL import Image
         import tempfile
         CF_BITMAP = 2
         
         image = Image.fromstring(image.format, (image.width, image.height), image.get_image_data().data)
         image = image.convert('RGB').transpose(Image.FLIP_TOP_BOTTOM)
         fd, filename = tempfile.mkstemp('.bmp')
         try:
             with os.fdopen(fd, 'w') as file:
                 image.save(file, 'BMP')
             if not isinstance(filename, unicode):
                 filename = filename.decode('mbcs')
             image = windll.user32.LoadImageW(None, filename, 0, 0, 0, 0x10)
             windll.user32.OpenClipboard(self._hwnd)
             windll.user32.EmptyClipboard()
             windll.user32.SetClipboardData(CF_BITMAP, image)
             windll.user32.CloseClipboard()
         finally:
             os.remove(filename)
     else:
         image.save(os.path.expanduser('~/punyverse.png'))
Example #25
0
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8,
           case_sensitive=True):
    """Creates a QR-Code from string data.
    
    Args:
      data: string: The data to encode in a QR-code. If a unicode string is
          supplied, it will be encoded in UTF-8.
      version: int: The minimum version to use. If set to 0, the library picks
          the smallest version that the data fits in.
      level: int: Error correction level. Defaults to 'L'.
      hint: int: The type of data to encode. Either QR_MODE_8 or QR_MODE_KANJI.
      case_sensitive: bool: Should string data be encoded case-preserving?
    Returns:
      A (version, size, image) tuple, where image is a size*size PIL image of
      the QR-code.
    """
    if isinstance(data, unicode):
        data = data.encode('utf8')
    elif not isinstance(data, basestring):
        raise ValueError('data argument must be a string.')
    version = int(version)
    if level not in levels:
        raise ValueError('Invalid error-correction level.')
    if hint not in hints:
        raise ValueError('Invalid encoding mode.')
    if case_sensitive:
        version, size, data = _encode(data, version, level, hint, True)
    else:
        version, size, data = _encode(data, version, level, hint, False)
    
    im = Image.fromstring('L', (size, size), data)
    return (version, size, im)
def quiver_image(X, Y, U, V):
    pylab.figure(1)
    pylab.quiver(X, Y, U, V)
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    pil_image = Image.fromstring('RGB', canvas.get_width_height(), canvas.tostring_rgb())
    return pil_image
Example #27
0
def decompress(img, frm):
    """Available formats (Storage):
            'Image': misura compression algorithm (Image)
            'ImageM3': legacy Misura3 compression algorithm (Binary)
            other: any PIL supported format (Binary)
    """
    fr = open(img, 'rb').read()
    if frm == 'ImageM3':
        return (fr, (640, 480))
    try:
        fr = bitmap.decompress(fr)
        if frm == 'ImageBMP':
            return fr
        fr = fr[::-1]
        im = Image.fromstring('L', (640, 480), fr)
        im = im.convert('L')
        if frm == 'Image':
            return (np.asarray(im), im.size)
        else:
            sio = StringIO.StringIO()
            im.save(sio, frm)
            im.save('debug.' + frm, frm)
            sio.seek(0)
            r = sio.read()
            return (r, im.size)
    except:
        logging.debug(format_exc())
        logging.debug('Error reading image', img)
        r = ('', (0, 0))
    return r
Example #28
0
    def on_key(self, *args):
        ESCAPE = '\033'
        if args[0] == ESCAPE or args[0] == 'q':
            os._exit(0)
        elif args[0] == 'r':
            self.rotate = [0., 0., 0.]
            self.translate = [0., 0., 0.]
            self.scale = 1.0
        elif args[0] == 'l':
            if self.lights:
                self.lights = False
            else:
                self.lights = True
        elif args[0] == 's':
            try:
                from PIL import Image
            except:
                try:
                    import Image
                except:
                    raise ImportError("Cannot Find appropriate Image Library, for Saving")
            vp = GL.glGetIntegerv(GL.GL_VIEWPORT)
            pixel_array = GL.glReadPixels(0,0,vp[2],vp[3],GL.GL_RGB,GL.GL_UNSIGNED_BYTE)

            pilImage = Image.fromstring(mode="RGB",size=(vp[3],vp[2]),data=pixel_array)
            pilImage = pilImage.transpose(Image.FLIP_TOP_BOTTOM)
            pilImage.save(self.save_file + str(self.save_count) + '.png')
            self.save_count += 1 
Example #29
0
 def get(self):
     res = StringIO()
     surf = self._cam.get_image()
     buf = pygame.image.tostring(surf, 'RGBA')
     img = Image.fromstring('RGBA', (CAMERA_WIDTH, CAMERA_HEIGHT), buf)
     img.save(res, 'JPEG')
     return {'content':b64encode(res.getvalue())}
Example #30
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
        """
        """
        start_time = time()
        
        #
        # Mapnik can behave strangely when run in threads, so place a lock on the instance.
        #
        if global_mapnik_lock.acquire():
            try:
                if self.mapnik is None:
                    self.mapnik = get_mapnikMap(self.mapfile)
                    logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile)

                self.mapnik.width = width
                self.mapnik.height = height
                self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax))
            
                img = mapnik.Image(width, height)
                mapnik.render(self.mapnik, img) 
            except:
                self.mapnik = None
                raise
            finally:
                # always release the lock
                global_mapnik_lock.release()

        img = Image.fromstring('RGBA', (width, height), img.tostring())
        
        logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %dx%d in %.3f from %s', width, height, time() - start_time, self.mapfile)
    
        return img
    def capture_screen(self):
        """Captures Chameleon framebuffer.

        @return An Image object.
        """
        return Image.fromstring(
            'RGB', self.get_resolution(),
            self.chameleond_proxy.DumpPixels(self.port_id).data)
Example #32
0
def convertWXToPIL(wximg):
    h = wximg.GetHeight()
    w = wximg.GetWidth()
    # convert wxImage to string array RGBRGBRGB...
    soutpix = wximg.GetData()
    # convert string array to an RGB Pil image
    pilimage = Image.fromstring('RGB', (w, h), soutpix)
    return pilimage
 def arrayToImage(a):
     """
     Converts a gdalnumeric array to a 
     Python Imaging Library Image.
     """
     i=Image.fromstring('L',(a.shape[1],a.shape[0]),
             (a.astype('b')).tostring())
     return i   
Example #34
0
def format_single_image(from_camera):
    from_camera_string = pygame.image.tostring(from_camera)
    image = Image.fromstring(from_camera_string)
    #Format the image to the appropriate size
    image = image.resize((64, 36))
    image_list = np.array([list(image.getdata())])
    image_list = format_X(image_list, [64, 36])
    return image_list
def array2image(a):
    if a.typecode() == Numeric.UnsignedInt8:
        mode = "L"
    elif a.typecode() == Numeric.Float32:
        mode = "F"
    else:
        raise ValueError, "unsupported image mode"
    return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
Example #36
0
    def trimFrames (self, debug):
	self.trimDATA = []
	for i in range (self.nFrames):
		width, height, data, centerX, centerY, isRLE = self.frames[i]
		if width > 0 and height > 0:
			temp = 0
			# Top
			top = height
			width, height, data, centerX, centerY = self.trim(width, height, data, centerX, centerY)
			top -= height
			# Right
			im = Image.fromstring("P", (width, height), data)
			im.putpalette(self.PILPalette)
			im2 = im.transpose (2)
			data = im2.tostring()
			right = width
			height, width, data, temp, temp = self.trim(height, width, data, centerX, centerY)
			right -= width
			# Bottom
			im = Image.fromstring("P", (height, width), data)
			im.putpalette(self.PILPalette)
			im2 = im.transpose (2)
			data = im2.tostring()
			bottom = height
			width, height, data, temp, temp = self.trim(width, height, data, centerX, centerY)
			bottom -= height
			#Left
			im = Image.fromstring("P", (width, height), data)
			im.putpalette(self.PILPalette)
			im2 = im.transpose (2)
			data = im2.tostring()
			left = width
			height, width, data, centerY, centerX = self.trim(height, width, data, centerY, centerX)
			left -= width
			# Back to Top
			im = Image.fromstring("P", (height, width), data)
			im.putpalette(self.PILPalette)
			im2 = im.transpose (2)
			data = im2.tostring()
			#print len(data)
			self.frames[i] = [width, height, data, centerX, centerY, isRLE]
			self.trimDATA.append (list([i, width, left, right, height, top, bottom, centerX, centerY]))
		else:
			self.trimDATA.append (list([i, width, 0, 0, height, 0, 0, centerX, centerY]))
	if debug:
		self.dumpTrim()
Example #37
0
def toGray(surf):
    img = Image.fromstring("RGB", surf.get_size(),
                           pygame.image.tostring(surf, "RGB", False))
    img = img.convert("L")
    img = img.convert("RGB")
    newsurf = pygame.image.fromstring(img.tostring(), surf.get_size(), "RGB",
                                      False)
    return newsurf
Example #38
0
 def rgb24image(self, img_data, width, height, rowstride):
     assert has_PIL
     if rowstride > 0:
         assert len(img_data) == rowstride * height
     else:
         assert len(img_data) == width * 3 * height
     return Image.fromstring("RGB", (width, height), img_data, 'raw', 'RGB',
                             rowstride, 1)
Example #39
0
def CVtoPIL(img):
    """converts CV image to PIL image"""
    cv_img = cv.CreateMatHeader(
        cv.GetSize(img)[1],
        cv.GetSize(img)[0], cv.CV_8UC1)
    #cv.SetData(cv_img, pil_img.tostring())
    pil_img = Image.fromstring("L", cv.GetSize(img), img.tostring())
    return pil_img
Example #40
0
def array2image(a):
    if a.typecode() == np.uint8:
        mode = "L"
    elif a.typecode() == np.float32:
        mode = "F"
    else:
        raise ValueError, "unsupported image mode %s" % (a.typecode())
    return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
Example #41
0
def get_cached_issue_image(issue_number):
    memcache_key = "issue_%d_image" % issue_number
    cached_values = memcache.get_multi([memcache_key, memcache_key + "_width"])
    image_data = cached_values.get(memcache_key)
    width = cached_values.get(memcache_key + "_width")
    if image_data and width:
        return Image.fromstring("RGBA", (width, BADGE_HEIGHT), image_data)
    return None
Example #42
0
def BuildVoteImage(nModels,
                   data,
                   values,
                   trueValues=[],
                   sortTrueVals=0,
                   xScale=10,
                   yScale=2,
                   addLine=1):
    """ constructs the actual image

    **Arguments**

      - nModels: the number of models in the composite

      - data: the results of voting

      - values: predicted values for each example

      - trueValues: true values for each example

      - sortTrueVals: if nonzero the votes will be sorted so
        that the _trueValues_ are in order, otherwise the sort
        is by _values_

      - xScale: number of pixels per vote in the x direction

      - yScale: number of pixels per example in the y direction

      - addLine: if nonzero, a purple line is drawn separating
         the votes from the examples

    **Returns**

      a PIL image
      
  """
    nData = len(data)
    data = numpy.array(data, numpy.integer)
    if sortTrueVals and trueValues != []:
        order = numpy.argsort(trueValues)
    else:
        order = numpy.argsort(values)
    data = [data[x] for x in order]
    maxVal = max(numpy.ravel(data))
    data = data * 255 / maxVal
    img = Image.fromstring('L', (nModels, nData), data.astype('B').tostring())

    if addLine:
        img = img.convert('RGB')
        canvas = ImageDraw.Draw(img)
        if trueValues != []:
            canvas.line([(nModels - 3, 0), (nModels - 3, nData)],
                        fill=(128, 0, 128))
        else:
            canvas.line([(nModels - 2, 0), (nModels - 2, nData)],
                        fill=(128, 0, 128))
    img = img.resize((nModels * xScale, nData * yScale))
    return img
Example #43
0
def get_image():
    global im2arrF
    while True:
        # Send read frame request
        send_msg(0x41, 0x53, 0, 0, '\xC0\x7E\x00\x00')

        try:
            ret9  = dev.read(0x81, 0x3F60, 1000)
            ret9 += dev.read(0x81, 0x3F60, 1000)
            ret9 += dev.read(0x81, 0x3F60, 1000)
            ret9 += dev.read(0x81, 0x3F60, 1000)
        except usb.USBError as e:
            sys.exit()

        #  Let's see what type of frame it is
        #  1 is a Normal frame, 3 is a Calibration frame
        #  6 may be a pre-calibration frame
        #  5, 10 other... who knows.
        status = ret9[20]
        #print ('%5d'*21 ) % tuple([ret9[x] for x in range(21)])

        if status == 1:
            #  Convert the raw calibration data to a string array
            calimg = Image.fromstring("I", (208,156), ret9, "raw", "I;16")

            #  Convert the string array to an unsigned numpy int16 array
            im2arr = numpy.asarray(calimg)
            im2arrF = im2arr.astype('uint16')

        if status == 3:
            #  Convert the raw calibration data to a string array
            img = Image.fromstring("I", (208,156), ret9, "raw", "I;16")

            #  Convert the string array to an unsigned numpy int16 array
            im1arr = numpy.asarray(img)
            im1arrF = im1arr.astype('uint16')

            #  Subtract the calibration array from the image array and add an offset
            additionF = (im1arrF-im2arrF)+ 800

            #  convert to an image and display with imagemagick
            disp_img = toimage(additionF)
            #disp_img.show()
            
            return disp_img
Example #44
0
def surf_grey(surface):
    rect = surface.get_rect()
    image_string = pygame.image.tostring(surface, 'RGB', False)
    image_pil = Image.fromstring('RGB', rect.size, image_string)
    image_pil = image_pil.convert('L')
    image_pil = image_pil.convert('RGB')
    image_string = image_pil.tostring()
    surface = pygame.image.fromstring(image_string, rect.size, 'RGB', False)
    return surface
Example #45
0
    def _get_image_from_camera(self):
        if self.camera is None:
            return None

        surface = self.camera.get_image()
        imgstr = pygame.image.tostring(surface, 'RGB')
        image = Image.fromstring('RGB', surface.get_size(), imgstr)

        return image
Example #46
0
    def image(self):
        """Extracts image data as PIL Image"""

        # PIL "raw" decoder modes for the various image dataTypes
        dataTypesDec = {
            1: 'F;16S',  #16-bit LE signed integer
            2: 'F;32F',  #32-bit LE floating point
            6: 'F;8',  #8-bit unsigned integer
            7: 'F;32S',  #32-bit LE signed integer
            9: 'F;8S',  #8-bit signed integer
            10: 'F;16',  #16-bit LE unsigned integer
            11: 'F;32',  #32-bit LE unsigned integer
            14: 'F;8',  #binary
        }

        # get relevant Tags
        tag_root = 'root.ImageList.1'
        data_offset = int(self.tags["%s.ImageData.Data.Offset" % tag_root])
        data_size = int(self.tags["%s.ImageData.Data.Size" % tag_root])
        data_type = int(self.tags["%s.ImageData.DataType" % tag_root])
        im_width = int(self.tags["%s.ImageData.Dimensions.0" % tag_root])
        im_height = int(self.tags["%s.ImageData.Dimensions.1" % tag_root])

        if self.debug > 0:
            print "Notice: image data in %s starts at %s" % (os.path.split(
                self._filename)[1], hex(data_offset))
            print "Notice: image size: %sx%s px" % (im_width, im_height)

        # check if image DataType is implemented, then read
        if data_type in dataTypesDec:
            decoder = dataTypesDec[data_type]
            if self.debug > 0:
                print "Notice: image data type: %s ('%s'), read as %s" % (
                    data_type, dataTypes[data_type], decoder)
                t1 = time.time()
            self._f.seek(data_offset)
            rawdata = self._f.read(data_size)
            im = Image.fromstring('F', (im_width, im_height), rawdata, 'raw',
                                  decoder)
            if self.debug > 0:
                t2 = time.time()
                print "| read image data: %.3g s" % (t2 - t1)
        else:
            raise Exception(
                "Cannot extract image data from %s: unimplemented DataType (%s:%s)."
                % (os.path.split(
                    self._filename)[1], data_type, dataTypes[data_type]))

        # if image dataType is BINARY, binarize image
        # (i.e., px_value>0 is True)
        if data_type == 14:
            # convert Image to 'L' to apply point operation
            im = im.convert('L')
            # binarize
            im = im.point(lambda v: v > 0 or False)

        return im
Example #47
0
def wx_image_to_pil(wx_image, copy_alpha=True):
    """Converts a wx.Image to PIL.Image."""
    pil_image = Image.new("RGB", wx_image.GetSize())
    pil_image.fromstring(wx_image.Data)
    if wx_image.HasAlpha() and copy_alpha:
        pil_image = pil_image.convert("RGBA")
        alpha = Image.fromstring("L", wx_image.GetSize(), wx_image.AlphaData)
        pil_image.putalpha(alpha)
    return pil_image
 def _iplimage_as_pil_image(self):
     """Converts an IplImage into a PIL Image
     
     Right now, ctypes-opencv can convert 1-channel (uint8|int32|float32) 
     IplImages or uint8 (BGR|BGRA) IplImages. Whether the image's data 
     array is shared or copied to PIL.Image depends on how PIL decodes
     the array (i.e. via function PIL.Image.fromstring()).
     """
     try:
         mode, decoder = _ipl_depth_and_nc_to_pil_mode_and_decoder[self.depth, self.nChannels]
     except KeyError:
         raise TypeError("Don't know how to convert the image. Check its depth and/or its number of channels.")
     if self.origin == 0:
         return Image.fromstring(mode, (self.width, self.height), self.data_as_string(), 
             "raw", decoder, self.widthStep, 1)
     else:
         return Image.fromstring(mode, (self.width, self.height), self.data_as_string(), 
             "raw", decoder, self.widthStep, -1)
Example #49
0
 def bitmap(self, byte):
     c = byte - (self.lochar)
     d = self.charloc[c * 4:(c + 1) * 4]
     (offs, width) = unpack(">HH", d)
     data = "".join([
         self.rasterize(ord(self.chardata[(offs >> 3) + (n * self.modulo)]))
         for n in range(self.ysize)
     ])
     return Image.fromstring("L", (width, self.ysize), data)
def open_exr_as_rgbf_images( exr_file ):
    file = OpenEXR.InputFile( exr_file )
    pt = Imath.PixelType( Imath.PixelType.FLOAT )
    dw = file.header()['dataWindow']
    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    rgbf = [Image.fromstring("F", size, file.channel(c, pt)) for c in "RGB"]

    return rgbf
Example #51
0
def export_image(image):
    from PIL import Image, ImageChops
    stream = image.stream
    (width, height) = image.srcsize
    filters = stream.get_filters()
    fp = StringIO.StringIO()
    if len(filters) == 1 and filters[0] in LITERALS_DCT_DECODE:
        ext = 'jpg'
    else:
        ext = 'img'
    if ext == 'jpg':
        raw_data = stream.get_rawdata()
        if LITERAL_DEVICE_CMYK in image.colorspace:
            ifp = BytesIO(raw_data)
            i = Image.open(ifp)
            i = ImageChops.invert(i)
            i = i.convert('RGB')
            i.save(fp, 'JPEG')
        else:
            fp.write(raw_data)
    elif image.bits == 1:
        i = Image.fromstring('1', image.srcsize, stream.get_data())
        i.save(fp, 'PNG')
        ext = 'png'
    elif image.bits == 8 and image.colorspace[0] is LITERAL_DEVICE_RGB:
        i = Image.fromstring('RGB', image.srcsize, stream.get_data())
        i.save(fp, 'PNG')
        ext = 'png'
    elif image.bits == 8 and image.colorspace[0] is LITERAL_DEVICE_GRAY:
        i = Image.fromstring('L', image.srcsize, stream.get_data())
        i.save(fp, 'PNG')
        ext = 'png'
    else:
        fp.write(stream.get_data())
        bytes_as_hex = b2a_hex(stream.get_rawdata()[:4])
        if bytes_as_hex == '89504e47':
            ext = 'png'
        elif bytes_as_hex == '47494638':
            ext = 'gif'
        elif bytes_as_hex.startswith('424d'):
            ext = 'bmp'
    fp.seek(0)

    return ext, fp.read()
Example #52
0
    def renderTile(self, tile):
        driver = gdal.GetDriverByName('GTiff')
        images = self.client.images_by_bbox(tile.bounds(), output='full')

        if not images: return None

        # Set up a target oam.Image ----------------------------------------
        target = oam.Image("unused",
                           tile.bbox,
                           tile.width,
                           tile.height,
                           crs=images[0].crs)

        # Build input gdal datasource --------------------------------------
        vrtdoc = self.build_vrt(target, images)
        vrt = vrtdoc.toxml('utf-8')
        source_ds = gdal.Open(vrt)

        assert source_ds, \
            "%s couldn't open the VRT: %s" % (type(self),vrt)

        # Prepare output gdal datasource -----------------------------------
        try:
            destination_ds = driver.Create('/vsimem/output', width, height, 3)

            assert destination_ds is not None, \
                "%s couldn't make the file: /vsimem/output" % type(self)

            merc = osr.SpatialReference()
            merc.ImportFromProj4(srs)
            destination_ds.SetProjection(merc.ExportToWkt())

            # note that 900913 points north and east
            x, y = xmin, ymax
            w, h = xmax - xmin, ymin - ymax

            gtx = [x, w / width, 0, y, 0, h / height]
            destination_ds.SetGeoTransform(gtx)

            # Create rendered area -------------------------------------
            gdal.ReprojectImage(source_ds, destination_ds)

            r, g, b = [
                destination_ds.GetRasterBand(i).ReadRaster(
                    0, 0, width, height) for i in (1, 2, 3)
            ]
            data = ''.join([''.join(pixel) for pixel in zip(r, g, b)])
            area = Image.fromstring('RGB', (width, height), data)

            buffer = StringIO.StringIO()
            area.save(buffer, self.extension)
            buffer.seek(0)
            tile.data = buffer.read()

        finally:
            driver.Delete("/vsimem/output")
Example #53
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom,
                   auth):
        """
        """
        start_time = time()

        #
        # Mapnik can behave strangely when run in threads, so place a lock on the instance.
        #
        if global_mapnik_lock.acquire():
            try:
                if self.mapnik is None:
                    self.mapnik = get_mapnikMap(self.mapfile)
                    logging.debug(
                        'TileStache.Mapnik.ImageProvider.renderArea() %.3f to load %s',
                        time() - start_time, self.mapfile)

                #hack to only objects user is authorised to see
                #NOTE: check if auth_column is set?
                for la in self.mapnik.layers:
                    query = """(SELECT * 
                                FROM {}
                                WHERE {} IN ({})
                               ) AS {}""".format(
                        self.table, self.auth_column,
                        ', '.join(str(i) for i in auth), self.table)
                    la.datasource = mapnik.PostGIS(
                        host=str(self.host),
                        geometry_field=str(self.geometry_field),
                        key_field=str(self.key_field),
                        user=str(self.user),
                        password=str(self.password),
                        dbname=str(self.dbname),
                        table=query)

                self.mapnik.width = width
                self.mapnik.height = height
                self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax))

                img = mapnik.Image(width, height)
                mapnik.render(self.mapnik, img)
            except:
                self.mapnik = None
                raise
            finally:
                # always release the lock
                global_mapnik_lock.release()

        img = Image.fromstring('RGBA', (width, height), img.tostring())

        logging.debug(
            'TileStache.Mapnik.ImageProvider.renderArea() %dx%d in %.3f from %s',
            width, height,
            time() - start_time, self.mapfile)

        return img
Example #54
0
def imsave(fname, arr, format_str=None):
    """Save an image to disk.

    Parameters
    ----------
    fname : str or file-like object
        Name of destination file.
    arr : ndarray of uint8 or float
        Array (image) to save.  Arrays of data-type uint8 should have
        values in [0, 255], whereas floating-point arrays must be
        in [0, 1].
    format_str: str
        Format to save as, this is defaulted to PNG if using a file-like
        object; this will be derived from the extension if fname is a string

    Notes
    -----
    Currently, only 8-bit precision is supported.

    """
    arr = np.asarray(arr).squeeze()

    if arr.ndim not in (2, 3):
        raise ValueError("Invalid shape for image array: %s" % arr.shape)

    if arr.ndim == 3:
        if arr.shape[2] not in (3, 4):
            raise ValueError("Invalid number of channels in image array.")

    # Image is floating point, assume in [0, 1]
    if np.issubdtype(arr.dtype, float):
        arr = arr * 255

    arr = arr.astype(np.uint8)

    if arr.ndim == 2:
        mode = 'L'

    elif arr.shape[2] in (3, 4):
        mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]]

        # Force all integers to bytes
        arr = arr.astype(np.uint8)

    # default to PNG if file-like object
    if not isinstance(fname, string_types) and format_str is None:
        format_str = "PNG"

    try:
        img = Image.frombytes(mode, (arr.shape[1], arr.shape[0]),
                              arr.tostring())
    except AttributeError:
        img = Image.fromstring(mode, (arr.shape[1], arr.shape[0]),
                               arr.tostring())

    img.save(fname, format=format_str)
Example #55
0
class TestContext( BaseContext ):
    initialPosition = (0,0,0) # set initial camera position, tutorial does the re-positioning
    drawCapture = 0
    capturedImage = 0
    useStringDraw = 0
    reverseShape = 0
    def Render( self, mode = 0):
        BaseContext.Render( self, mode )
        glTranslatef(1.5,0.0,-6.0);
        glRotated( time.time()%(8.0)/8 * -360, 1,0,0)
        drawcube.drawCube()
        width, height = self.getViewPort()
        red = glReadPixelsub(0,0, width, height,GL_RED, outputType=None)
        print 'refcount for array', sys.getrefcount( red )
        red = glReadPixels(0,0, width, height,GL_RED, GL_UNSIGNED_BYTE, outputType=None)
        print 'refcount for string', sys.getrefcount( red )

        

##		glTranslatef(-5,0.0,0);
##		drawcube.drawCube()
##
##		# draw different scene
##		pixels = glReadPixelsub(0,0, width, height,GL_RGB, outputType=None)
##		pixels[:,:, 0] = red
##		glDrawPixelsub(GL_RGB, pixels)
        
    def OnIdle( self, ):
        self.triggerRedraw(1)
        return 1
    def OnInit( self ):
        """Load the image on initial load of the application"""
        self.addEventHandler( 'keypress', name='s', function=self.OnSave )
        self.addEventHandler( 'keypress', name='d', function=self.OnViewUB )
        self.addEventHandler( 'keypress', name='t', function=self.OnUseStringDraw )
        self.addEventHandler( 'keypress', name='r', function=self.OnReverseShape )
    def OnSave( self, event):
        self.SaveTo( 'test.jpg' )
    def SaveTo( self, filename, format="JPEG" ):
        try:
            from PIL import Image # get PIL's functionality...
        except ImportError, err:
            # old style?
            import Image
        width, height = self.getViewPort()
        glPixelStorei(GL_PACK_ALIGNMENT, 1)
        data = glReadPixelsub(0, 0, width, height, GL_RGB, outputType=None)
        assert data.shape == (width,height,3), """Got back array of shape %r, expected %r"""%(
            data.shape,
            (width,height,3),
        )
        image = Image.fromstring( "RGB", (width, height), data.tostring() )
        image = image.transpose( Image.FLIP_TOP_BOTTOM)
        image.save( filename, format )
        print 'Saved image to %s'% (os.path.abspath( filename))
        return image
Example #56
0
def GeneratePILImageFromNumpyImage(numpy_image):

    (h, w, depth) = numpy_image.shape

    if depth == 3: format = 'RGB'
    elif depth == 4: format = 'RGBA'

    pil_image = PILImage.fromstring(format, (w, h), numpy_image.data)

    return pil_image
Example #57
0
    def __init__(self, fb):
        self.font = ImageFont.load('6by6tall.pil')
        self.textSize = self.font.getsize(self.text)
        self.textimg = Image.new('RGB',
                                 (self.textSize[0] + 4, self.textSize[1]),
                                 (0, 0, 0))
        textdraw = ImageDraw.Draw(self.textimg)
        textdraw.text((0, 0), self.text, font=self.font, fill=(255, 255, 255))

        gradient = np.ndarray(shape=(fb.size[1], fb.size[0], 3), dtype='uint8')
        colnorm = 1.0 / (fb.size[0] - 1.0)
        rownorm = 1.0 / (fb.size[1] - 1.0)
        for row in range(0, fb.size[1]):
            nrow = row * rownorm
            for col in range(0, fb.size[0]):
                ncol = col * colnorm

                color = np.array([1.0, 1.0, 1.0])
                if ncol < 0.15:
                    color *= 0.05 + (ncol * 0.95 / 0.15)
                elif ncol >= 0.85:
                    color *= 0.05 + ((1.0 - ncol) * 0.95 / 0.15)

                dbc = (max(0, 0.75 - nrow)**2 +
                       (2.0 * ncol - 1.0)**2) / (0.75**2 + 1.0**2)
                color -= np.array([0.0, 0.85, 0.85]) * dbc

                gradient[row, col, :] = [
                    min(255, max(0, int(v * 255))) for v in color
                ]

        self.gradient = Image.fromstring('RGB', fb.size, gradient.tostring())

        backdrop = np.ndarray(shape=(fb.size[1], fb.size[0] * 3, 3),
                              dtype='uint8')
        for row in range(0, fb.size[1]):
            for col in range(0, fb.size[0] * 3):
                rn = random.randrange(0, 64)
                rn2 = random.randrange(0, 128)
                backdrop[row, col, :] = [0, rn * rn2 / 255, rn]

        self.backdrop = Image.fromstring('RGB', (fb.size[0] * 3, fb.size[1]),
                                         backdrop.tostring())
Example #58
0
 def save_image(self, image, name="nao_image", show=False):
     width = image[0]
     height = image[1]
     array = image[6]
     string = str(bytearray(array))
     im = Image.fromstring("RGB", (width, height), string)
     name = name + ".png"
     im.save(name, "PNG")
     if show:
         im.show()
Example #59
0
 def timerEvent(self, e):
     try:
         val = buf.get_nowait()
         img = Image.fromstring("L", (640, 480), val)
         rgb = img.convert("RGB").tostring()
         self.setPixmap(
             QPixmap(QImage(rgb, 640, 480, 24, None, 1,
                            QImage.IgnoreEndian)))
     except Empty:
         pass
Example #60
0
    def grabFrame(self):
        """Returns a snapshot from the device as PIL.Image.Image object."""

        data, w, h, orientation = self.grabRawFrame()
        try:
            return Image.frombytes("RGB", (w, h), data, "raw", "BGR", 0,
                                   orientation)
        except:
            return Image.fromstring("RGB", (w, h), data, "raw", "BGR", 0,
                                    orientation)