33 from __future__
import print_function
35 from io
import BytesIO
39 from PIL
import ImageOps
43 import cairocffi
as cairo
48 if img_msg._type ==
'sensor_msgs/CompressedImage':
49 pil_img = Image.open(BytesIO(img_msg.data))
50 if pil_img.mode.startswith(
'BGR'):
55 if img_msg.encoding
in [
'mono8',
'8UC1']:
57 elif img_msg.encoding ==
'rgb8':
59 elif img_msg.encoding ==
'bgr8':
61 elif img_msg.encoding
in [
'bayer_rggb8',
'bayer_bggr8',
'bayer_gbrg8',
'bayer_grbg8']:
63 elif img_msg.encoding
in [
'bayer_rggb16',
'bayer_bggr16',
'bayer_gbrg16',
'bayer_grbg16']:
65 if img_msg.is_bigendian:
69 elif img_msg.encoding ==
'mono16' or img_msg.encoding ==
'16UC1':
71 if img_msg.is_bigendian:
75 elif img_msg.encoding ==
'32FC1':
77 if img_msg.is_bigendian:
81 elif img_msg.encoding ==
'rgba8':
83 elif img_msg.encoding ==
'bgra8':
86 raise Exception(
"Unsupported image format: %s" % img_msg.encoding)
87 pil_img = Image.frombuffer(
88 pil_mode, (img_msg.width, img_msg.height), img_msg.data,
'raw', mode, 0, 1)
91 if pil_mode ==
'I;16':
92 pil_img = pil_img.convert(
'I').point(
lambda i: i * (1. / 256.)).convert(
'L')
94 if pil_img.mode ==
'F':
95 pil_img = pil_img.point(
lambda i: i * (1. / 256.)).convert(
'L')
96 pil_img = ImageOps.autocontrast(pil_img)
97 pil_img = ImageOps.invert(pil_img)
99 if rgba
and pil_img.mode !=
'RGBA':
100 pil_img = pil_img.convert(
'RGBA')
104 except Exception
as ex:
105 print(
'Can\'t convert image: %s' % ex, file=sys.stderr)
110 rgb2bgr = (0, 0, 1, 0,
113 return pil_img.convert(
'RGB', rgb2bgr)
118 data = array.array(
'c')
119 data.fromstring(pil_img.tostring())
121 return cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, w, h)