本文整理匯總了Python中cv2.imencode方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.imencode方法的具體用法?Python cv2.imencode怎麽用?Python cv2.imencode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.imencode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: make_web
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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')
示例2: main
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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()
示例3: get_producer_wrappers
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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)
]
示例4: mini_crop_by_landmarks
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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
示例5: callback
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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)
開發者ID:PacktPublishing,項目名稱:ROS-Programming-Building-Powerful-Robots,代碼行數:21,代碼來源:image_recognition.py
示例6: gen_livestream
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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')
示例7: get_frame
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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()
示例8: write_log
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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]
示例9: recoginize_weapons
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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
示例10: recoginize_abilities
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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
示例11: recoginize_deadly_weapons
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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
示例12: callback
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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)
示例13: infer
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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]
示例14: pack_img
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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())
示例15: write_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import imencode [as 別名]
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)