def convert_to_cvmat(surface, surface_width, surface_height):
    """
    works with FORMAT_RGB24
    it should work with FORMAT_ARGB32 too but the transparency will be ignored.
    """
    # print("surface format = {}".format(surface.get_format()))
    # assert surface.get_format() == cairo.FORMAT_RGB24

    buf = surface.get_data()
    # print("format={}, given_surface_width:{}, actual_surface_width:{}, buf size: {}".format( surface.get_format(), surface_width, surface.get_width(), len(buf)))

    # if surface.get_width() != surface_width:
    #     surface.write_to_png("error.png")
        

    np_converted = np.ndarray(shape=(surface_width, surface_height),
                              dtype=np.uint32,
                              buffer=buf)

    # for r bitwise AND with 0x00ff0000
    r_filter = int("00ff0000", 16)
    g_filter = int("0000ff00", 16)
    b_filter = int("000000ff", 16)

    np_r_filtered = np.bitwise_and(np_converted, r_filter)
    np_r_shifted = np.right_shift(np_r_filtered, 16)
    np_r = np.expand_dims(np_r_shifted, axis=-1)

    np_g_filtered = np.bitwise_and(np_converted, g_filter)
    np_g = np.expand_dims(np.right_shift(np_g_filtered, 8), axis=-1)

    np_b = np.expand_dims(np.bitwise_and(np_converted, b_filter), axis=-1)

    # cv2 uses BGR format so concatenated in this order

    combined_32 = np.concatenate([np_b, np_g, np_r], axis=2)

    combined = combined_32.astype(np.uint8)

    return combined
Categories: python

0 Comments

Leave a Reply

Your email address will not be published.