Bokeh image format standards and interoperability

Maybe this will be useful:

from base64 import b64decode

import cv2
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Button
from bokeh.plotting import figure

img_jpeg = b64decode(
    'iVBORw0KGgoAAAANSUhEUgAAADIAAAAOBAMAAACfqVJUAAAAHlBMVEUAAAAAAwCKLY3jF17xWyICq65Qlc8js1T2qhmnzTbxGUeMAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAACVSURBVBjTpY89DsIwDIWfRRF087sB6sCMyhHIAbp078TMgroy9gq5LXYSooqOfYqsF3+Jf0BU6c9IcjvI6bUlJiDO78EJIXYVJRXptHEeRyP22PPC7Cy2EUcnKQOmkPrwHIHnpNQNWT5OvLi1oa7/LMB1ouZqqES0CUCXm6+Iz9aER9/5bKyYZZ9w7y91n0KKDjf86QvVrhIPSsvLCwAAAABJRU5ErkJggg==')
arr = np.fromstring(img_jpeg, np.uint8)
frame = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
orig_img = frame[::-1].copy().view(dtype=np.uint32)

pw = ph = 100
current_angle = 0
p = figure(aspect_ratio=1, x_range=(0, pw), y_range=(0, ph))


def mk_data(image):
    ih, iw, _ = image.shape
    return dict(image=[image], dw=[iw], dh=[ih], x=[(pw - iw) / 2], y=[(ph - ih) / 2])


src = ColumnDataSource(data=mk_data(orig_img))
p.image_rgba(image='image', x='x', y='y', dw='dw', dh='dh', source=src)


# From https://github.com/jrosebr1/imutils/blob/master/imutils/convenience.py#L41.
def rotate_bound(image, angle):
    (h, w) = image.shape[:2]
    (cX, cY) = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY
    return cv2.warpAffine(image, M, (nW, nH))


b = Button(label='Rotate!')


def rotate_img_by_15_deg():
    global current_angle
    current_angle += 15
    img = rotate_bound(orig_img.view(dtype=np.uint8), current_angle)
    src.data = mk_data(img.view(dtype=np.uint32))


b.on_click(rotate_img_by_15_deg)

curdoc().add_root(column(p, b))
3 Likes