cv_util.py
Go to the documentation of this file.
1 import base64
2 import imghdr
3 import os.path
4 import re
5 
6 import cv2
7 import numpy as np
8 import rospy
9 
10 
11 base64_and_filepath_image_pattern = re.compile(r'((?:/9j/)(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)? ?|/\S+\.(?:jpeg|jpg|png|gif))')
12 
13 
14 def encode_image_cv2(img, quality=90):
15  encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
16  result, encimg = cv2.imencode('.jpg', img, encode_param)
17  b64encoded = base64.b64encode(encimg).decode('ascii')
18  return b64encoded
19 
20 
21 def decode_image_cv2(b64encoded):
22  bin = b64encoded.split(",")[-1]
23  bin = base64.b64decode(bin)
24  bin = np.frombuffer(bin, np.uint8)
25  img = cv2.imdecode(bin, cv2.IMREAD_COLOR)
26  return img
27 
28 
29 def is_base64_image(b64encoded):
30  try:
31  decode_image_cv2(b64encoded)
32  except Exception as e:
33  rospy.logerr(str(e))
34  return False
35  return True
36 
37 
39  if base64_and_filepath_image_pattern.match(text) is None:
40  return None
41 
42  if os.path.exists(text):
43  path = text
44  if imghdr.what(path) in ['jpeg', 'jpg', 'png', 'gif']:
45  with open(path, 'rb') as f:
46  return f.read()
47  else:
48  succ = is_base64_image(text)
49  if succ:
50  bin = text.split(",")[-1]
51  bin = base64.b64decode(bin)
52  bin = np.frombuffer(bin, np.uint8)
53  return bin
54 
55 
57  texts = base64_and_filepath_image_pattern.split(text)
58  target_texts = list(filter(lambda x: x is not None and len(x.strip()) > 0, texts))
59 
60  split_texts = ['']
61  imgs_list = []
62 
63  texts = []
64  imgs = []
65  for text in target_texts:
66  img = get_image_from_text(text)
67  if img is None:
68  split_texts.append(text)
69  imgs_list.append(imgs)
70  imgs = []
71  else:
72  imgs.append(img)
73 
74  if len(imgs) > 0:
75  imgs_list.append(imgs)
76  if len(split_texts) > 0:
77  if len(split_texts[0]) == 0 and len(imgs_list[0]) == 0:
78  split_texts = split_texts[1:]
79  imgs_list = imgs_list[1:]
80  return imgs_list, split_texts
def extract_media_from_text(text)
Definition: cv_util.py:56
def encode_image_cv2(img, quality=90)
Definition: cv_util.py:14
def decode_image_cv2(b64encoded)
Definition: cv_util.py:21
def get_image_from_text(text)
Definition: cv_util.py:38
def is_base64_image(b64encoded)
Definition: cv_util.py:29


rostwitter
Author(s):
autogenerated on Sat Jun 24 2023 02:40:41