Python cv2.imencode() Examples

The following are 30 code examples for showing how to use cv2.imencode(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module cv2 , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: rl_data.py    License: Apache License 2.0 12 votes vote down vote up
def make_web(queue):
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    def gen():
        while True:
            frame = queue.get()
            _, frame = cv2.imencode('.JPEG', frame)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    try:
        app.run(host='0.0.0.0', port=8889)
    except:
        print('unable to open port') 
Example 2
Project: gabriel   Author: cmusatyalab   File: opencv_adapter.py    License: Apache License 2.0 7 votes vote down vote up
def get_producer_wrappers(self):
        async def producer():
            _, frame = self._video_capture.read()
            if frame is None:
                return None

            frame = self._preprocess(frame)
            _, jpeg_frame = cv2.imencode('.jpg', frame)

            input_frame = gabriel_pb2.InputFrame()
            input_frame.payload_type = gabriel_pb2.PayloadType.IMAGE
            input_frame.payloads.append(jpeg_frame.tostring())

            extras = self._produce_extras()
            if extras is not None:
                input_frame.extras.Pack(extras)

            return input_frame

        return [
            ProducerWrapper(producer=producer, source_name=self._source_name)
        ] 
Example 3
Project: MobileNetV2-PoseEstimation   Author: PINTO0309   File: runner.py    License: MIT License 7 votes vote down vote up
def infer(image, model='cmu', resize='0x0', resize_out_ratio=4.0):
    """

    :param image:
    :param model:
    :param resize:
    :param resize_out_ratio:
    :return: coco_style_keypoints array
    """
    w, h = model_wh(resize)
    e = get_estimator(model, resize)

    # estimate human poses from a single image !
    image = common.read_imgfile(image, None, None)
    if image is None:
        raise Exception('Image can not be read, path=%s' % image)
    humans = e.inference(image, resize_to_default=(w > 0 and h > 0), upsample_size=resize_out_ratio)
    image_h, image_w = image.shape[:2]

    if "TERM_PROGRAM" in os.environ and 'iTerm' in os.environ["TERM_PROGRAM"]:
        image = TfPoseEstimator.draw_humans(image, humans, imgcopy=False)
        image_str = cv2.imencode(".jpg", image)[1].tostring()
        print("\033]1337;File=name=;inline=1:" + base64.b64encode(image_str).decode("utf-8") + "\a")

    return [(eval.write_coco_json(human, image_w, image_h), human.score) for human in humans] 
Example 4
Project: object-detection   Author: cristianpb   File: camera_opencv.py    License: MIT License 6 votes vote down vote up
def img_to_base64(self, img):
        """encode as a jpeg image and return it"""
        buffer = cv2.imencode('.jpg', img)[1].tobytes()
        jpg_as_text = base64.b64encode(buffer)
        base64_string = jpg_as_text.decode('utf-8')
        return base64_string 
Example 5
Project: face_landmark_dnn   Author: junhwanjang   File: landmark_augment.py    License: MIT License 6 votes vote down vote up
def mini_crop_by_landmarks(self, sample_list, pad_rate, img_format):
        """
        Crop full image to mini. Only keep valid image to save
        Args:
            sample_list: (image, landmarks)
            pad_rate: up scale rate
            img_format: "RGB" or "BGR"
        Return:
            new sample list
        Raises:
            No
        """
        new_sample_list = []
        for sample in sample_list:
            image = cv2.imread(sample[0])
            if img_format == 'RGB':
                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            landmarks = sample[1]
            (x1, y1, x2, y2), _, _, _ = self.get_bbox_of_landmarks(image, landmarks, pad_rate, 0.5)
            new_sample_list.append(
                (cv2.imencode(".jpg", image[y1:y2, x1:x2])[1], landmarks - (x1, y1))
            )
            return new_sample_list 
Example 6
Project: ROS-Programming-Building-Powerful-Robots   Author: PacktPublishing   File: image_recognition.py    License: MIT License 6 votes vote down vote up
def callback(self, image_msg):
        cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, "bgr8")
        # copy from
        # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/imagenet/classify_image.py
        image_data = cv2.imencode('.jpg', cv_image)[1].tostring()
        # Creates graph from saved GraphDef.
        softmax_tensor = self._session.graph.get_tensor_by_name('softmax:0')
        predictions = self._session.run(
            softmax_tensor, {'DecodeJpeg/contents:0': image_data})
        predictions = np.squeeze(predictions)
        # Creates node ID --> English string lookup.
        node_lookup = classify_image.NodeLookup()
        top_k = predictions.argsort()[-self.use_top_k:][::-1]
        for node_id in top_k:
            human_string = node_lookup.id_to_string(node_id)
            score = predictions[node_id]
            if score > self.score_threshold:
                rospy.loginfo('%s (score = %.5f)' % (human_string, score))
                self._pub.publish(human_string) 
Example 7
Project: Gather-Deployment   Author: huseinzol05   File: app.py    License: MIT License 6 votes vote down vote up
def gen_livestream():
    global last_frame
    while True:
        if app.queue.qsize():
            frame = base64.b64decode(app.queue.get().split('base64')[-1])
            last_frame = frame
        else:
            if last_frame is None:
                fh = open(d+"/static/black.jpg", "rb")
                frame = fh.read()
                fh.close()
            else:
                frame = last_frame
        if last_frame:
            img_np = np.array(Image.open(io.BytesIO(frame)))
            img_np = detect_object(img_np)
            frame = cv2.imencode('.jpg', cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB))[1].tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') 
Example 8
Project: Gather-Deployment   Author: huseinzol05   File: opencv.py    License: MIT License 6 votes vote down vote up
def get_frame(self):
        _, frame = self.video.read()
        img = cv2.cvtColor(frame.copy(), cv2.COLOR_BGR2RGB)
        image_np_expanded = np.expand_dims(img, axis = 0)
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        scores = detection_graph.get_tensor_by_name('detection_scores:0')
        classes = detection_graph.get_tensor_by_name('detection_classes:0')
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')
        (boxes, scores, classes, num_detections) = sess.run(
            [boxes, scores, classes, num_detections],
            feed_dict = {image_tensor: image_np_expanded},
        )
        vis_util.visualize_boxes_and_labels_on_image_array(
            frame,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates = True,
            line_thickness = 8,
        )
        # return BGR, cv2 will returned BGR to RGB
        return cv2.imencode('.jpg', frame)[1].tobytes() 
Example 9
Project: rec-attend-public   Author: renmengye   File: full_model_pack.py    License: MIT License 6 votes vote down vote up
def write_log(self, results):
    """Process results
    Args:
      results: y_out, s_out
    """
    inp = results['_batches'][0]
    y_out = results['y_out']
    s_out = results['s_out']
    with h5py.File(self.dataset.h5_fname, 'r+') as h5f:
      print inp['idx_map']
      for ii in xrange(y_out.shape[0]):
        idx = inp['idx_map'][ii]
        group = h5f[self.dataset.get_str_id(idx)]
        if 'instance_pred' in group:
          del group['instance_pred']
        for ins in xrange(y_out.shape[1]):
          y_out_arr = y_out[ii, ins]
          y_out_arr = (y_out_arr * 255).astype('uint8')
          y_out_str = cv2.imencode('.png', y_out_arr)[1]
          group['instance_pred/{:02d}'.format(ins)] = y_out_str
        if 'score_pred' in group:
          del group['score_pred']
        group['score_pred'] = s_out[ii] 
Example 10
Project: training_results_v0.6   Author: mlperf   File: rl_data.py    License: Apache License 2.0 6 votes vote down vote up
def make_web(queue):
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    def gen():
        while True:
            frame = queue.get()
            _, frame = cv2.imencode('.JPEG', frame)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    try:
        app.run(host='0.0.0.0', port=8889)
    except:
        print('unable to open port') 
Example 11
Project: IkaLog   Author: hasegaw   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def recoginize_weapons(self, weapons_list):
        payload = []

        for img_weapon in weapons_list:
            result, img_weapon_png = cv2.imencode('.png', img_weapon)
            payload.append(img_weapon_png.tostring())

        response = self._request_func(
            '/api/v1/recoginizer/weapon',
            payload,
        )

        # Validate the response.
        assert response is not None, 'NO API Response.'
        assert response.get('status', None) == 'ok', 'API Error.'

        # Decode the response.
        ret = []
        for entry in response['weapons']:
            ret.append(entry.get('weapon', None))

        return ret 
Example 12
Project: IkaLog   Author: hasegaw   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def recoginize_abilities(self, abilities_list):
        payload = []

        for img_ability in abilities_list:
            result, img_ability_png = cv2.imencode('.png', img_ability)
            payload.append(img_ability_png.tostring())

        response = self._request_func(
            '/api/v1/recoginizer/ability',
            payload,
        )

        # Validate the response.
        assert response is not None, 'NO API Response.'
        assert response.get('status', None) == 'ok', 'API Error.'

        # Decode the response.
        ret = []
        for entry in response['abilities']:
            ret.append(entry.get('ability', None))

        return ret 
Example 13
Project: IkaLog   Author: hasegaw   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def recoginize_deadly_weapons(self, deadly_weapons_list):
        if len(deadly_weapons_list) == 0:
            return None
        images = self.pack_deadly_weapons_image(deadly_weapons_list)

        payload = {
            'game_language': Localization.get_game_languages()[0],
            'sample_height': deadly_weapons_list[0].shape[0],
            'sample_width': deadly_weapons_list[0].shape[1],
            'samples': cv2.imencode('.png', images)[1].tostring()
        }

        response = self._request_func(
            '/api/v1/recoginizer/deadly_weapon',
            payload,
        )

        if response.get('status', None) != 'ok':
            return {'status': 'error'}

        return response 
Example 14
Project: ros_tensorflow   Author: cong   File: ros_tensorflow_classify.py    License: Apache License 2.0 6 votes vote down vote up
def callback(self, image_msg):
        cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, "bgr8")
        image_data = cv2.imencode('.jpg', cv_image)[1].tostring()

        # Creates graph from saved GraphDef.
        softmax_tensor = self._session.graph.get_tensor_by_name('softmax:0')
        predictions = self._session.run(
            softmax_tensor, {'DecodeJpeg/contents:0': image_data})
        predictions = np.squeeze(predictions)

        # Creates node ID --> English string lookup.
        node_lookup = self.load(PATH_TO_LABELS, PATH_TO_UID)
        top_k = predictions.argsort()[-self.use_top_k:][::-1]
        for node_id in top_k:
            
            if node_id not in node_lookup:
                human_string = ''
            else:
                human_string = node_lookup[node_id]

            score = predictions[node_id]
            if score > self.score_threshold:
                rospy.loginfo('%s (score = %.5f)' % (human_string, score))
                self._pub.publish(human_string) 
Example 15
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: recordio.py    License: Apache License 2.0 5 votes vote down vote up
def pack_img(header, img, quality=95, img_fmt='.jpg'):
    """Pack an image into ``MXImageRecord``.

    Parameters
    ----------
    header : IRHeader
        Header of the image record.
        ``header.label`` can be a number or an array. See more detail in ``IRHeader``.
    img : numpy.ndarray
        Image to be packed.
    quality : int
        Quality for JPEG encoding in range 1-100, or compression for PNG encoding in range 1-9.
    img_fmt : str
        Encoding of the image (.jpg for JPEG, .png for PNG).

    Returns
    -------
    s : str
        The packed string.

    Examples
    --------
    >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3]
    >>> id = 2574
    >>> header = mx.recordio.IRHeader(0, label, id, 0)
    >>> img = cv2.imread('test.jpg')
    >>> packed_s = mx.recordio.pack_img(header, img)
    """
    assert cv2 is not None
    jpg_formats = ['.JPG', '.JPEG']
    png_formats = ['.PNG']
    encode_params = None
    if img_fmt.upper() in jpg_formats:
        encode_params = [cv2.IMWRITE_JPEG_QUALITY, quality]
    elif img_fmt.upper() in png_formats:
        encode_params = [cv2.IMWRITE_PNG_COMPRESSION, quality]

    ret, buf = cv2.imencode(img_fmt, img, encode_params)
    assert ret, 'failed to encode image'
    return pack(header, buf.tostring()) 
Example 16
Project: DOTA_models   Author: ringringyi   File: file_utils.py    License: Apache License 2.0 5 votes vote down vote up
def write_image(image_path, rgb):
  ext = os.path.splitext(image_path)[1]
  with gfile.GFile(image_path, 'w') as f:
    img_str = cv2.imencode(ext, rgb[:,:,::-1])[1].tostring()
    f.write(img_str) 
Example 17
Project: EdgeRealtimeVideoAnalytics   Author: RedisGears   File: server.py    License: Apache License 2.0 5 votes vote down vote up
def get_last(self):
        ''' Gets latest from camera and model '''
        p = self.conn.pipeline()
        p.xrevrange(self.camera, count=1)  # Latest frame
        p.xrevrange(self.boxes, count=1)   # Latest boxes
        cmsg, bmsg = p.execute()
        if cmsg:
            last_id = cmsg[0][0].decode('utf-8')
            label = f'{self.camera}:{last_id}'
            data = io.BytesIO(cmsg[0][1][self.field])
            img = Image.open(data)
            if bmsg:
                boxes = np.fromstring(bmsg[0][1]['boxes'.encode('utf-8')][1:-1], sep=',')
                label += ' people: {}'.format(bmsg[0][1]['people'.encode('utf-8')].decode('utf-8'))
                for box in range(int(bmsg[0][1]['people'.encode('utf-8')])):  # Draw boxes
                    x1 = boxes[box*4]
                    y1 = boxes[box*4+1]
                    x2 = boxes[box*4+2]
                    y2 = boxes[box*4+3]
                    draw = ImageDraw.Draw(img)
                    draw.rectangle(((x1, y1), (x2, y2)), width=5, outline='red')
            arr = np.array(img)
            arr = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)
            cv2.putText(arr, label, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 1, cv2.LINE_AA)
            ret, img = cv2.imencode('.jpg', arr)
            return img.tobytes()
        else:
            # TODO: put an 'we're experiencing technical difficlties' image
            pass 
Example 18
Project: dataflow   Author: tensorpack   File: noise.py    License: Apache License 2.0 5 votes vote down vote up
def _augment(self, img, q):
        enc = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, q])[1]
        return cv2.imdecode(enc, 1).astype(img.dtype) 
Example 19
Project: object-detection   Author: cristianpb   File: camera_pi.py    License: MIT License 5 votes vote down vote up
def img_to_base64(self, img):
        """encode as a jpeg image and return it"""
        buffer = cv2.imencode('.jpg', img)[1].tobytes()
        jpg_as_text = base64.b64encode(buffer)
        base64_string = jpg_as_text.decode('utf-8')
        return base64_string 
Example 20
Project: object-detection   Author: cristianpb   File: app.py    License: MIT License 5 votes vote down vote up
def image_preview(filename):
    w = request.args.get('w', None)
    h = request.args.get('h', None)
    date = request.args.get('date', None)

    try:
        im = cv2.imread(os.path.join(IMAGE_FOLDER, filename))
        if w and h:
            w, h = int(w), int(h)
            im = cv2.resize(im, (w, h))
        elif date:
            date = (datetime
                    .strptime(date, "%Y%m%d_%H%M%S")
                    .strftime("%d %b %-H:%M")
                    )
            img_h, img_w = im.shape[:-1]
            cv2.putText(
                    im, "{}".format(date), (0, int(img_h*0.98)),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        return Response(cv2.imencode('.jpg', im)[1].tobytes(),
                        mimetype='image/jpeg')

    except Exception as e:
        print(e)

    return send_from_directory('.', filename) 
Example 21
Project: object-detection   Author: cristianpb   File: camera_jetson.py    License: MIT License 5 votes vote down vote up
def img_to_base64(self, img):
        """encode as a jpeg image and return it"""
        buffer = cv2.imencode('.jpg', img)[1].tobytes()
        jpg_as_text = base64.b64encode(buffer)
        base64_string = jpg_as_text.decode('utf-8')
        return base64_string 
Example 22
Project: derplearning   Author: notkarol   File: util.py    License: MIT License 5 votes vote down vote up
def encode_jpg(image, quality):
    return cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tostring() 
Example 23
Project: web-document-scanner   Author: yushulx   File: camera.py    License: MIT License 5 votes vote down vote up
def get_video_frame(self):
        ret, frame = self.cap.read()
        if ret:
            frame, _ = self.scanner.detect_edge(frame)
            self.cached_frame = frame
            ret, jpeg = cv2.imencode('.jpg', frame)
            return jpeg.tobytes()
        else:
            return None 
Example 24
Project: web-document-scanner   Author: yushulx   File: camera.py    License: MIT License 5 votes vote down vote up
def capture_frame(self):
        ret, frame = self.cap.read()
        if ret:
            _, frame = self.scanner.detect_edge(frame, True)
            ret, jpeg = cv2.imencode('.jpg', frame)
            self.transformed_frame = jpeg.tobytes()
        else:
            return None 
Example 25
def cv_imwrite(write_path, img):
    cv2.imencode('.jpg', img, )[1].tofile(write_path)
    return 
Example 26
Project: vidgear   Author: abhiTronix   File: webgear.py    License: Apache License 2.0 5 votes vote down vote up
def __producer(self):
        """
        A asynchronous frame producer/generator for WebGear application.
        """
        # loop over frames
        while self.__isrunning:
            # read frame
            frame = self.stream.read()
            # break if NoneType
            if frame is None:
                break
            # reducer frames size if specified
            if self.__frame_size_reduction:
                frame = await reducer(frame, percentage=self.__frame_size_reduction)
            # handle JPEG encoding
            encodedImage = cv2.imencode(
                ".jpg",
                frame,
                [
                    cv2.IMWRITE_JPEG_QUALITY,
                    self.__jpeg_quality,
                    cv2.IMWRITE_JPEG_PROGRESSIVE,
                    self.__jpeg_progressive,
                    cv2.IMWRITE_JPEG_OPTIMIZE,
                    self.__jpeg_optimize,
                ],
            )[1].tobytes()
            # yield frame in byte format
            yield (
                b"--frame\r\nContent-Type:image/jpeg\r\n\r\n" + encodedImage + b"\r\n"
            )
            await asyncio.sleep(0.01) 
Example 27
Project: gabriel   Author: cmusatyalab   File: push_client.py    License: Apache License 2.0 5 votes vote down vote up
def send_frames(source):
    capture = cv2.VideoCapture(0)
    while True:
        _, frame = capture.read()
        _, jpeg_frame=cv2.imencode('.jpg', frame)
        input_frame = gabriel_pb2.InputFrame()
        input_frame.payload_type = gabriel_pb2.PayloadType.IMAGE
        input_frame.payloads.append(jpeg_frame.tostring())

        source.send(input_frame)
        time.sleep(0.1) 
Example 28
Project: gabriel   Author: cmusatyalab   File: producer_client.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    args = common.parse_num_sources_server_host()
    capture = cv2.VideoCapture(0)
    def gen_producer(n):
        text = 'client {}'.format(n)
        async def producer():
            _, frame = capture.read()
            cv2.putText(frame, text, ORG, FONT_FACE, FONT_SCALE, COLOR)
            _, jpeg_frame=cv2.imencode('.jpg', frame)
            input_frame = gabriel_pb2.InputFrame()
            input_frame.payload_type = gabriel_pb2.PayloadType.IMAGE
            input_frame.payloads.append(jpeg_frame.tostring())

            return input_frame
        return producer

    producer_wrappers = [
        ProducerWrapper(producer=gen_producer(i), source_name=str(i))
        for i in range(args.num_sources)
    ]
    client = WebsocketClient(
        args.server_host, common.WEBSOCKET_PORT, producer_wrappers, consumer)
    client.launch() 
Example 29
Project: stagesepx   Author: williamfzc   File: toolbox.py    License: MIT License 5 votes vote down vote up
def np2b64str(frame: np.ndarray) -> str:
    buffer = cv2.imencode(".png", frame)[1].tostring()
    return b64encode(buffer).decode() 
Example 30
Project: opencv-engine   Author: thumbor   File: engine_cv3.py    License: MIT License 5 votes vote down vote up
def read(self, extension=None, quality=None):
        if quality is None:
            quality = self.context.config.QUALITY

        options = None
        extension = extension or self.extension
        try:
            if FORMATS[extension] == 'JPEG':
                options = [cv2.IMWRITE_JPEG_QUALITY, quality]
        except KeyError:
            # default is JPEG so
            options = [cv2.IMWRITE_JPEG_QUALITY, quality]

        try:
            if FORMATS[extension] == 'WEBP':
                options = [cv2.IMWRITE_WEBP_QUALITY, quality]
        except KeyError:
            options = [cv2.IMWRITE_JPEG_QUALITY, quality]

        success, buf = cv2.imencode(extension, self.image, options or [])
        data = buf.tostring()

        if FORMATS[extension] == 'JPEG' and self.context.config.PRESERVE_EXIF_INFO:
            if hasattr(self, 'exif') and self.exif != None:
                img = JpegFile.fromString(data)
                img._segments.insert(0, ExifSegment(self.exif_marker, None, self.exif, 'rw'))
                data = img.writeString()

        return data