Exemple #1
0
def saveImage(array, path):
    if array.dtype == np.bool:
        img = frombytes(mode='1', size=array.shape[::-1], data=np.packbits(array, axis=1))
        img.save(path)
    else:
        tifffile.imsave(path, array)
    print(f"'{path}' saved")
def bytearray_toimg(*datas, show=1):
    """ Basic usage:bytearray_toimg(np_array),
        convert a numpy array to image and show it
        if the last argument is set to 1 by default or by user.
        This function accept multiple arrays, show
        all of them or return the first one converted.
    """
    if show == 1:
        for data in datas:
            frombytes(mode='1',
                      size=data.shape[::-1],
                      data=np.packbits(data, axis=1)).show()
    else:
        for data in datas:
            return frombytes(mode='1',
                             size=data.shape[::-1],
                             data=np.packbits(data, axis=1))
 def do_live_view(self, *args):
     if self.video is not None:
         select((self.video, ), (), ())
         data = self.video.read_and_queue()
         self.image = frombytes(
             'RGB', (self.framesize['size_x'], self.framesize['size_y']),
             data)
         self.photo = PhotoImage(self.image)
         self.x_canvas.create_image(800 / 2, 800 / 2, image=self.photo)
         self.root.after(3, self.do_live_view)
def show_image(image_bytes, image_size):
    screen_width = root.winfo_width()
    screen_height = root.winfo_height()

    global im
    try:
        im = frombytes('RGB', image_size, image_bytes)
    except:
        return

    im = im.resize((screen_width, screen_height))
    im = PhotoImage(im)
    lbImage['image'] = im
    lbImage.image = im
Exemple #5
0
def save_array_img(mat, fp, img_format='png'):
    """
	Save numpy ndarray as an image.
	
	:param mat: Two-dimensional ndarray to be saved.
	:param fp: The path to save the image at or a file object.
	"""
    assert isinstance(mat, ndarray)
    if mat.size <= 0:
        raise ValueError('Cannot store arrays without elements as image')
    if len(mat.shape) == 1:
        mat = mat.reshape((mat.shape[0], 1))
    assert len(mat.shape) == 2
    if img_format not in {
            'bmp',
            'png',
            'raw',
            'tiff',
            'gif',
    }:
        raise TypeError(
            'only lossless image formats that have metadata are supported, '
            'otherwise data gets corrupted (in ways that do not approximate the original data)'
        )
    assert img_format == 'png', 'only png is implemented (metadata not yet implemented for others)'  # todo
    sz = mat.dtype.itemsize
    assert ((sz &
             (sz - 1)) == 0), 'only powers of two bytes per cell are supported'
    img_width = mat.shape[0]
    img_height = int(ceil(mat.shape[1] * sz / 4.))
    meta = PngImagePlugin.PngInfo()
    meta.add_text('Description',
                  META_DESCRIPTION.format(str(mat.dtype), *mat.shape))
    meta.add_text('Software', META_SOFTWARE)
    meta.add_text('dtype', str(mat.dtype))
    padding = b''
    if sz < 4:
        pad_len = int(img_width * img_height * 4 - mat.size * sz)
        padding = b'\00' * pad_len
        meta.add_text('padding', str(pad_len))
    data = mat.tobytes() + padding
    img = frombytes(mode='RGBA', size=(img_width, img_height), data=data)
    img.save(fp, format=img_format, pnginfo=meta)
Exemple #6
0
 def receive(self):
     while self.enableReiceive:
         try:
             len_struct = self.socket.recv(4)
             if len_struct:
                 lens = struct.unpack('i', len_struct)[0]
                 body = self.socket.recv(lens)
                 ty = body.decode('utf8')
                 if ty == "pic":
                     d = self.socket.recv(12)
                     data = struct.unpack('iii', d)
                     width, height, pic_len = data
                     body = self.tcpPieceRecv(pic_len, self.socket, 1024)
                     try:
                         im = frombytes(data=body,
                                        size=(width, height),
                                        mode="RGB",
                                        decoder_name='raw')
                         self.pic_signal.emit(im.toqpixmap())
                     except:
                         STD("图片错误")
                 elif ty == "response":
                     res_len = struct.unpack('i', self.socket.recv(4))[0]
                     response = self.socket.recv(res_len)
                     self.consoleSignal.emit(response.decode("utf8"))
                 elif ty == "filelist":
                     res_len = struct.unpack('i', self.socket.recv(4))[0]
                     response = self.tcpPieceRecv(res_len, self.socket,
                                                  1024)
                     data = json.loads(response.decode('utf8'))
                     data['list'] = data['list'][:300]
                     self.listSignal.emit(data['list'])
                     self.pwdSignal.emit(data['pwd'])
                 elif ty == 'file':
                     size = struct.unpack('i', self.socket.recv(4))[0]
                     data = self.tcpPieceRecv(size, self.socket, 1024)
                     self.fileSignal.emit(data)
         except:
             pass
     print("线程退出成功")
Exemple #7
0
def create_random_content_image(path: str) -> Image:
    array = bytes(randint(0, 255) for _ in range(100 * 100 * 3))
    image = frombytes('RGB', (100, 100), array)
    image.save(path)
    return image
Exemple #8
0
    def logImage(self,
                 tag,
                 images,
                 csc=None,
                 h=None,
                 w=None,
                 maxOutputs=3,
                 **kwargs):
        """
		Log image(s).
		
		Accepts either a single encoded image as a bytes/bytearray, or one or
		more images as a 3- or 4-D numpy array in the form CHW or NCHW.
		"""

        if isinstance(images, (bytes, bytearray)):
            """
			"Raw" calling convention: `image` contains an image file, and all
			arguments are mandatory. Image is logged encoded as-is
			"""

            metadata, reject, tag = self._commonTagLogic("images",
                                                         tag=tag + "/image",
                                                         **kwargs)
            if reject: return self

            val = TfImage(height=int(h),
                          width=int(w),
                          colorspace=int(csc),
                          imageData=images).asValue(tag, metadata)
            with self._lock:
                return self._stageValue(val)
        elif isinstance(images, (list, np.ndarray)):
            """
			"Numpy" calling convention: `image` is a numpy ndarray shaped (N,C,H,W).
			Conversion is to PNG -z 9. The precise transformation depends on the
			number of channels, datatype and content.
			"""

            #
            # Expand dimensionality
            #
            if isinstance(images, np.ndarray) and images.ndim == 3:
                images = images[np.newaxis, ...]

            #
            # Iterate.
            #
            for i, image in enumerate(images):
                #
                # Do not output more than the limit of images.
                #
                if i >= maxOutputs:
                    break

                #
                # Follow TF naming algorithm for image batches.
                #
                if i == 0 and maxOutputs == 1:
                    metadata, reject, tag = self._commonTagLogic("images",
                                                                 tag=tag +
                                                                 "/image",
                                                                 **kwargs)
                else:
                    metadata, reject, tag = self._commonTagLogic(
                        "images", tag=tag + "/image/" + str(i), **kwargs)
                if reject: continue

                #
                # Follow TF type-conversion algorithm for individual images.
                #
                # If   c == 1: Assume grayscale.
                # Elif c == 2: Assume grayscale+alpha.
                # Elif c == 3: Assume RGB.
                # Elif c == 4: Assume RGBA.
                # Else: raise
                #
                c, h, w = image.shape
                if c == 1:
                    csc = TfColorSpace.GRAYSCALE
                    mode = "L"
                elif c == 2:
                    csc = TfColorSpace.GRAYSCALE_ALPHA
                    mode = "LA"
                elif c == 3:
                    csc = TfColorSpace.RGB
                    mode = "RGB"
                elif c == 4:
                    csc = TfColorSpace.RGBA
                    mode = "RGBA"
                else:
                    raise ValueError("Invalid image specification!")

                #
                # (continued TF type-conversion algorithm for individual images)
                #
                # If   image.dtype == np.uint8:
                #     pass
                # Elif image.min() >= 0:
                #     image /= image.max()/255.0
                #     image  = image.astype(np.uint8)
                # Else:
                #     image.scale( s.t. min >= -127 and max <= 128 )
                #     image += 127
                #
                if image.dtype == np.uint8:
                    pass
                elif image.min() >= 0:
                    image *= +255.0 / image.max()
                else:
                    fMin, fMax = abs(-127.0 / image.min()), abs(+128.0 /
                                                                image.max())
                    image *= np.minimum(fMin, fMax)
                    image += +127.0
                image = image.astype(np.uint8)

                #
                # Encode as PNG using an in-memory buffer as the "file" stream.
                #

                from PIL.Image import frombytes
                stream = BytesIO()
                image = frombytes(mode, (w, h),
                                  image.transpose(1, 2, 0).tobytes("C"))
                image.save(stream, format="png",
                           optimize=True)  # Always PNG -z 9
                image = stream.getvalue()
                stream.close()

                #
                # Log the image.
                #
                val = TfImage(height=int(h),
                              width=int(w),
                              colorspace=int(csc),
                              imageData=image).asValue(tag, metadata)
                with self._lock:
                    self._stageValue(val)
        else:
            raise ValueError("Unable to interpret image arguments!")

        return self