Пример #1
0
def toImage(arr):
    if arr.type().bytes == 1:
        # need to swap coordinates btw array and image (with [::-1])
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    else:
        arr_c = arr - arr.min()
        arr_c *= (255./arr_c.max())
        arr = arr_c.astype(UInt8)
        # need to swap coordinates btw array and image (with [::-1])
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    return im
Пример #2
0
def toImage(arr):
    if arr.dtype != 'uint8' :
        arr_c = arr - arr.min()
        maxi = arr_c.max()
        if maxi > 0 : 
            arr_c *= (255./maxi)
        arr = arr_c.astype('uint8')
        print("Array shape %s, size %d, type %s, range %d-%d, mean %.1f, std %.1f"%(repr(arr.shape), arrx.size, arr.dtype, arr.min(), arr.max(), arr.mean(), arr.std()))
    # need to swap coordinates btw array and image (with [::-1])
    if len(arr.shape) == 2 :
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    else :
        im = Image.frombytes('RGB', (arr.shape[1],arr.shape[0]), arr.tostring())
    return im
Пример #3
0
    def get_last_environment_map(self):
        if self.last_environment_map is None:
            faceh = self.cubemap_face_yres
            facew = self.cubemap_face_xres

            nchan = self.last_optical_images['posy'].shape[2]
            imnx = numpy.empty( (faceh*3,facew*4,nchan), dtype = numpy.uint8)
            if nchan == 4:
                # make background transparent (alpha channel = 0)
                initvalue = 0
            else:
                # make background white
                initvalue = 255
            imnx.fill(initvalue)

            yi0 = faceh
            yi1 = 2*faceh

            xi0 = 0
            xi1 = facew
            imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['posy']

            xi0 = 2*facew
            xi1 = 3*facew
            imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['negy']

            xi0 = 3*facew
            xi1 = 4*facew
            imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['negx']

            xi0 = facew
            xi1 = 2*facew
            imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['posx']

            yi0 = 0
            yi1 = faceh
            imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['negz']

            yi0 = 2*faceh
            yi1 = 3*faceh
            imnx[yi0:yi1,xi0:xi1,:] = self.last_optical_images['posz']

            if nchan == 3:
                im = Image.frombytes('RGB',(imnx.shape[1],imnx.shape[0]),imnx.tostring())
            elif nchan == 4:
                im = Image.frombytes('RGBA',(imnx.shape[1],imnx.shape[0]),imnx.tostring())
            im = im.transpose( Image.FLIP_TOP_BOTTOM )
            self.last_environment_map = im
        return self.last_environment_map
Пример #4
0
def savepng():
    buffer = ( GLubyte * (3*width*height) )(0)
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer)
    image = Image.frombytes(mode="RGB", size=(width, height), data=buffer)
    image = image.transpose(Image.FLIP_TOP_BOTTOM)
    now_time = datetime.datetime.now()
    image.save('screen/'+now_time.strftime("%Y%m%d-%H%M")+'.png', format = 'png')
Пример #5
0
    def save(filename, width, height, fmt, pixels, flipped=False):
        image = PILImage.frombytes(fmt.upper(), (width, height), pixels)

        if flipped:
            image = image.transpose(PILImage.FLIP_TOP_BOTTOM)
        image.save(filename)
        return True
Пример #6
0
    def printViewer(self):
        """Save current buffer to filename in format"""
        from global_vars import CAIDViewerWildcard
        # Create a save file dialog
        dialog = wx.FileDialog ( None, style = wx.SAVE | wx.OVERWRITE_PROMPT
                               , wildcard=CAIDViewerWildcard)
        # Show the dialog and get user input
        if dialog.ShowModal() == wx.ID_OK:
            filename="test.jpeg"
            try:
                filename = dialog.GetPath()
            except:
                pass
            ext = filename.split('.')[-1]
            if ext == "jpeg":
                fmt="JPEG"
            if ext == "png":
                fmt="PNG"

            import Image # get PIL's functionality...
            import os
            x,y,width,height = glGetDoublev(GL_VIEWPORT)
            width = int(width)
            height = int(height)
            glPixelStorei(GL_PACK_ALIGNMENT, 1)
            data = glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE)
#            image = Image.fromstring( "RGB", (width, height), data )
            image = Image.frombytes( "RGB", (width, height), data )
            image = image.transpose( Image.FLIP_TOP_BOTTOM)
            image.save( filename, fmt )
            self.statusbar.SetStatusText("Image has been saved in " + filename)

        # Destroy the dialog
        dialog.Destroy()
def getColour(IP, PORT):
    """
First get an image from Nao, then show it on the screen with PIL.
    :param IP:
    :param PORT:
"""


    myBroker = ALBroker("myBroker",
        "0.0.0.0", # listen to anyone
        0, # find a free port and use it
        IP, # parent broker IP
        PORT) # parent broker port

    camProxy = ALProxy("ALVideoDevice", IP, PORT)
    resolution = 2 # VGA
    colorSpace = 11 # RGB


    videoClient = camProxy.subscribe("python_client", resolution, colorSpace, 5)

    t0 = time.time()

    # Get a camera image.
    # image[6] contains the image data passed as an array of ASCII chars.
    naoImage = camProxy.getImageRemote(videoClient)

    t1 = time.time()

    # Time the image transfer.
    #print "Runde: ", b

    camProxy.unsubscribe(videoClient)


    # Now we work with the image returned and save it as a PNG using ImageDraw
    # package.

    # Get the image size and pixel array.
    imageWidth = naoImage[0]
    imageHeight = naoImage[1]
    array = naoImage[6]

    #Create a PIL Image Instance from our pixel array.
    img0= Image.frombytes("RGB", (imageWidth, imageHeight), array)


    #frame=np.asarray(convert2pil(img0)[:,:])

    #object_rect2=detectColor(img0, RED_MIN,RED_MAX)
    frame=detectShape(img0, RED_MIN,RED_MAX)

    #frame=selectDetected(object_rect1,frame)

    #frame=selectDetected(object_rect2,frame)
    # currentImage = path+ "/camImage1cm.jpg"
    # cv2.imwrite(currentImage, frame)
    cv2.imshow('contour',frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Пример #8
0
def arrayToImage(a):
    """
    Converts a gdalnumeric array to a
    Python Imaging Library Image.
    """
    i=Image.frombytes('L',(a.shape[1],a.shape[0]),
            (a.astype('b')).tostring())
    return i
Пример #9
0
 def savepng(self):
     buffer = ( GLubyte * (3*800*600) )(0)
     glReadPixels(0, 0, 800, 600, GL_RGB, GL_UNSIGNED_BYTE, buffer)
     image = Image.frombytes(mode="RGB", size=(800, 600), data=buffer)
     image = image.transpose(Image.FLIP_TOP_BOTTOM)
     now_time = datetime.datetime.now()
     savename = 'screen/'+now_time.strftime("%Y%m%d-%H%M%S")+'.png'
     print 'save image to '+savename
     image.save(savename, format = 'png')
Пример #10
0
def addImage(snbFile,canvas,image,rels,element):
	imgFileName = "snote/"+rels[image.getAttribute("r:id")]
	imgStr = zipRead(snbFile,imgFileName)
	if imgFileName.endswith(".zdib"):
		imgStr = decompress(imgStr)
		width = ord(imgStr[5]) * 256 + ord(imgStr[4])
		height = ord(imgStr[9]) * 256 + ord(imgStr[8])
		try:
			img = Image.frombytes("RGBA",(width,height),imgStr[52:])
		except:
			img = Image.fromstring("RGBA",(width,height),imgStr[52:])
		canvas.drawInlineImage(alpha_to_color(img),0,0,595.27,841.89)
	else:
		style = imagePoss(element.getElementsByTagName("v:shape")[0].getAttribute("style"))
		img=Image.open(BytesIO(imgStr))
		canvas.drawInlineImage(img,style.left,style.bottom,style.width,style.height)
def mainModule(IP, PORT):
    """
    First get an image from Nao, then show it on the screen with PIL.
    :param IP:
    :param PORT:
    """
    myBroker = ALBroker("myBroker",
        "0.0.0.0", # listen to anyone
        0, # find a free port and use it
        IP, # parent broker IP
        PORT) # parent broker port

    camProxy = ALProxy("ALVideoDevice", IP, PORT)
    resolution = 2 # VGA
    colorSpace = 11 # RGB


    videoClient = camProxy.subscribe("python_client", resolution, colorSpace, 5)

    t0 = time.time()

    # Get a camera image.
    # image[6] contains the image data passed as an array of ASCII chars.
    naoImage = camProxy.getImageRemote(videoClient)

    t1 = time.time()

    # Time the image transfer.
    #print "Runde: ", b

    camProxy.unsubscribe(videoClient)


    # Now we work with the image returned and save it as a PNG using ImageDraw
    # package.

    # Get the image size and pixel array.
    imageWidth = naoImage[0]
    imageHeight = naoImage[1]
    array = naoImage[6]

    #Create a PIL Image Instance from our pixel array.
    img0= Image.frombytes("RGB", (imageWidth, imageHeight), array)

    frame = visualize(img0, dict)

    showImage('contour', frame)
Пример #12
0
def dotest(outputname, nostamp):
    plane = genbar()
    palette = (0,0,0, 255,255,255) + (128,128,128)*254
    try:    
        img = Image.frombytes("P", plane.size, plane.tobytes())
    except AttributeError:
        # note: https://github.com/python-pillow/Pillow/issues/63
        img = Image.fromstring("P", plane.size, plane.tostring())
    img.putpalette(palette)

    with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f:
        gif1 = f.name
    with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f:
        gif2 = f.name

    img.save(gif1, "GIF", optimize = 0)
    img.save(gif2, "GIF", transparency = 1, optimize = 0)

    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', '', 16)
    pdf.write(8, "Transparency")
    pdf.ln()
    pdf.write(8, "    Transparency")
    pdf.ln()
    pdf.write(8, "        Transparency")
    pdf.ln()
    pdf.image(gif1, x = 15, y = 15)

    pdf.write(8, "Transparency")
    pdf.ln()
    pdf.write(8, "    Transparency")
    pdf.ln()
    pdf.write(8, "        Transparency")
    pdf.ln()
    pdf.image(gif2, x = 15, y = 39)

    pdf.output(outputname, 'F')

    os.unlink(gif1)
    os.unlink(gif2)
Пример #13
0
    def _get_image_from_pdf(self, page_nr=1, max_width=None, max_height=None,
        angle=0, output_format='JPEG', restricted=False):
        """Render a pdf page as image."""
        if restricted and (page_nr > 1):
            raise ApplicationError.PermissionDenied(
                "Your are not allowed to see this document.")

        if self._doc.getNumPages() < page_nr:
            raise ApplicationError.InvalidArgument(
                "Bad page number: it should be < %s." %
                self._doc.getNumPages())
        import time
        self.logger.debug("Render image from pdf with opts width=%s, "\
            "height=%s, angle=%s, page_nr=%s." % (max_width, max_height, angle,
            page_nr))
        start = time.clock()
        splash = poppler.SplashOutputDev(poppler.splashModeRGB8, 3, False,
            (255, 255, 255), True, True)
        splash.startDoc(self._doc.getXRef())

        scale = self._get_optimal_scale(max_width, max_height, page_nr)
        self._doc.displayPage(splash, page_nr, 72*scale, 72*scale, -angle, True,
            True, False)

        bitmap = splash.getBitmap()
        new_width = bitmap.getWidth()
        new_height = bitmap.getHeight()
        if restricted and ((MVOConfig.Security.pdf_max_width < new_width)\
                or (MVOConfig.Security.pdf_max_height < new_height)):
            raise ApplicationError.PermissionDenied(
                "Your are not allowed to see this document.")

        pil = Image.frombytes('RGB', (new_width, new_height),
            bitmap.getDataPtr())
        temp_file = cStringIO.StringIO()
        pil.save(temp_file, "JPEG", quality=90)
        temp_file.seek(0)
        content = temp_file.read()
        self.logger.debug("Total Process Time: %s", (time.clock() - start))
        #header = [('content-type', 'image/jpeg'), ('content-length',
        #str(len(content)))]
        return('image/jpeg', content)
Пример #14
0
def image_to_pil(image):
    #
    #import Image
    """ Method will convert wx.Image to PIL Image """
    #pil = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
    #pil.fromstring(image.GetData())


    data = image.GetData()

    import sys
    if isinstance(image.GetData(), bytearray):
        if sys.version_info > (3, 0):
            data = bytes(data)
        else:
            data = str(data)
    pil = Image.frombytes('RGB', (image.GetWidth(), image.GetHeight()),
                          data)
    print pil
    return pil
Пример #15
0
    def export_define_bits(self, tag):
        png_buffer = BytesIO()
        image = None
        if isinstance(tag, TagDefineBitsJPEG3):

            tag.bitmapData.seek(0)
            tag.bitmapAlphaData.seek(0, 2)
            num_alpha = tag.bitmapAlphaData.tell()
            tag.bitmapAlphaData.seek(0)
            image = Image.open(tag.bitmapData)
            if num_alpha > 0:
                image_width = image.size[0]
                image_height = image.size[1]
                image_data = image.getdata()
                image_data_len = len(image_data)
                if num_alpha == image_data_len:
                    buff = ""
                    for i in range(0, num_alpha):
                        alpha = ord(tag.bitmapAlphaData.read(1))
                        rgb = list(image_data[i])
                        buff += struct.pack("BBBB", rgb[0], rgb[1], rgb[2], alpha)
                    image = Image.frombytes("RGBA", (image_width, image_height), buff)
        elif isinstance(tag, TagDefineBitsJPEG2):
            tag.bitmapData.seek(0)
            image = Image.open(tag.bitmapData)
        else:
            tag.bitmapData.seek(0)
            if self.jpegTables is not None:
                buff = BytesIO()
                self.jpegTables.seek(0)
                buff.write(self.jpegTables.read())
                buff.write(tag.bitmapData.read())
                buff.seek(0)
                image = Image.open(buff)
            else:
                image = Image.open(tag.bitmapData)

        self.export_image(tag, image)
Пример #16
0
def cv2_pil(cv_im):
    # Convert the cv image to a PIL image
    return Image.frombytes("L", cv.GetSize(cv_im), cv_im.tostring())
Пример #17
0
 def get_image(self):
     """Get a new image from the camera."""
     for _ in range(5): #HACK TODO document this
         im = cv.QueryFrame(self._cam)
     return Image.frombytes("RGB", cv.GetSize(im), im.tobytes(), "raw",
                             "BGR", 0, 1) 
Пример #18
0
		str_pos.append(n)
    	    if str0[n] != " " and str0[n-1] ==" ":
            	str_pos.append(n)
#    	print str_pos
#    	print len(str_pos)
#        print "line = ", (j) * (i+1) + i
#    	print " x =", str0[0:str_pos[0]]
#    	print " y = ", str0[str_pos[1]:str_pos[2]]
#    	print "value =", str0[str_pos[3]:str_pos[4]]
#    	print "conver str to int"
        if str_pos[3] == str_pos[4]:
    	    value = str0[str_pos[3]+1] 
        else:
    	    value = str0[str_pos[3]:(str_pos[4]+1)]
        if j * (i+1) + i >= 120:  
            byteArray = byteArray + value
#        print byteArray
        yx[j].append(value) 
#    	print "value =", value
fo.close() 

image = Image.frombytes("RGB", (300, 300), byteArray)
#image = Image.fromarray(yx, "RGB")
image.show()
image.save("test.png")
#print yx
#print byteArray
#image = Image.open(StringIO.StringIO(1024 * 1124)
#str_pos = []

Пример #19
0
def save_data(params):
	name = params.name
	gesture = params.gesture
	display = params.display
	controller = display.controller

	devices = controller.devices
	if len(devices) == 0:
		return 'no_device'

	frame = controller.frame()

	while not frame.is_valid:
		if(params._stop.is_set()):
			return 'exit'

		frame = controller.frame()

	hands = frame.hands
	controller.set_policy(Leap.Controller.POLICY_IMAGES)

	while len(hands) == 0:
		if(params._stop.is_set()):
			return 'exit'

		frame = controller.frame()
		hands = frame.hands

	# time.sleep(1)

	# while True:
	# 	if(params._stop.is_set()):
	# 		return 'exit'

	# 	frame = controller.frame()
	# 	hands = frame.hands

	# 	if len(hands) > 0:
	# 		if(params._stop.is_set()):
	# 			return 'exit'

	# 		confidence_now = hands[0].confidence

	# 		display.update_confidence_label(confidence_now)

	# 		if confidence_now >= display.confidence:
	# 			break

	image = frame.images[0]

	d = {}
	d['utc'] = str(datetime.datetime.utcnow())
	d['name'] = name
	d['gesture'] = gesture

	# print 'Confidence: ' + str(confidence_now)

	for hand in hands:
		if hand.is_valid:
			print 'Valid hand'
			if hand.is_right:
				which_hand = 'right_hand'
			else:
				which_hand = 'left_hand'

			hand_palm_position = hand.palm_position

			d[which_hand] = {}


			d[which_hand]['confidence'] = hand.confidence
			d[which_hand]['direction'] = (hand.direction-hand_palm_position).to_tuple()
			d[which_hand]['grab_strength'] = hand.grab_strength
			d[which_hand]['palm_normal'] = (hand.palm_normal-hand_palm_position).to_tuple()
			d[which_hand]['palm_position'] = (hand.palm_position-hand_palm_position).to_tuple()
			d[which_hand]['palm_velocity'] = hand.palm_velocity.to_tuple()
			d[which_hand]['palm_width'] = hand.palm_width
			d[which_hand]['sphere_center'] = (hand.sphere_center-hand_palm_position).to_tuple()
			d[which_hand]['sphere_radius'] = hand.sphere_radius
			d[which_hand]['stabilized_palm_position'] = (hand.stabilized_palm_position-hand_palm_position).to_tuple()

			arm = hand.arm
			d[which_hand]['arm'] = {}

			d[which_hand]['arm']['direction'] = arm.direction.to_tuple()
			d[which_hand]['arm']['elbow_position'] = (arm.elbow_position-hand_palm_position).to_tuple()
			d[which_hand]['arm']['wrist_position'] = (arm.wrist_position-hand_palm_position).to_tuple()

			fingers = hand.fingers

			for finger in fingers:
				if finger.type == Finger.TYPE_THUMB:
					which_finger = 'thumb'
				elif finger.type == Finger.TYPE_INDEX:
					which_finger = 'index'
				elif finger.type == Finger.TYPE_MIDDLE:
					which_finger = 'middle'
				elif finger.type == Finger.TYPE_RING:
					which_finger = 'ring'
				elif finger.type == Finger.TYPE_PINKY:
					which_finger = 'pinky'
				else:
					break

				d[which_hand][which_finger] = {}

				d[which_hand][which_finger]['direction'] = finger.direction.to_tuple()
				d[which_hand][which_finger]['length'] = finger.length
				d[which_hand][which_finger]['stabilized_tip_position'] = (finger.stabilized_tip_position-hand_palm_position).to_tuple()
				d[which_hand][which_finger]['tip_position'] = (finger.tip_position-hand_palm_position).to_tuple()
				d[which_hand][which_finger]['tip_velocity'] = finger.tip_velocity.to_tuple()
				d[which_hand][which_finger]['width'] = finger.width

				for i in range(4):
					bone = 'bone_' + str(i)

					d[which_hand][which_finger][bone] = {}

					d[which_hand][which_finger][bone]['center'] = (finger.bone(i).center-hand_palm_position).to_tuple()
					d[which_hand][which_finger][bone]['direction'] = finger.bone(i).direction.to_tuple()
					d[which_hand][which_finger][bone]['length'] = finger.bone(i).length
					d[which_hand][which_finger][bone]['width'] = finger.bone(i).width
					d[which_hand][which_finger][bone]['next_joint'] = (finger.bone(i).next_joint-hand_palm_position).to_tuple()
					d[which_hand][which_finger][bone]['prev_joint'] = (finger.bone(i).prev_joint-hand_palm_position).to_tuple()

		else:
			print 'Not a valid hand'

	ret = mongo.save(d, display.db_name, display.collection_name)

	if(ret.startswith('success')):
		[ret, oid] = ret.split(' ')

		if image.is_valid:
			print 'valid image'

			directory = os.path.join(os.getcwd(), 'images/')
			extension = '.png'
			tmp_file = 'tmp' + extension

			data = image.data

			barray = bytearray(image.width * image.height)
			for d in range(0, image.width * image.height - 1):
				barray[d] = data[d]

			img = Image.frombytes('L', (image.width, image.height), buffer(barray))
			img.save(directory + tmp_file)

			img = io.imread(directory + tmp_file)

			thresh = filters.threshold_isodata(img)
			bw_img = img > thresh

			io.imsave(directory + oid + extension, util.img_as_ubyte(bw_img))

			os.remove(directory + tmp_file)
		else:
			print 'invalid image'

		return ret + ' ' + oid + ' ' + display.db_name + ' ' + display.collection_name

	else:
		return ret
import Image, hashlib
from Crypto import Random
from Crypto.Cipher import AES
im = Image.open('heckert_gnu.png')
raw = im.tobytes()
IV = Random.new().read(AES.block_size)
#print raw
#print im
key = hashlib.sha256("password".encode()).digest()

mode = AES.MODE_ECB
encryptor = AES.new(key, mode, IV=IV)

encrypted_bytes = encryptor.encrypt(raw)

im_out = Image.frombytes(im.mode, im.size, encrypted_bytes)
im_out.save('ECB.png')