electronstudio / raylib-python-cffi

Python CFFI bindings for Raylib
http://electronstudio.github.io/raylib-python-cffi
Eclipse Public License 2.0
142 stars 29 forks source link

Create Image from CV2 Image #54

Closed madgrizzle closed 2 years ago

madgrizzle commented 2 years ago

I'm trying to create an Image from an opencv2 image. I'm VERY new to this and all I see in the docs is:

class pyray.Image(data, width, height, mipmaps, format)

What do I pass in the "data" argument?

electronstudio commented 2 years ago

Data is a pointer to the raw image data. It's just a chunk of memory containing the image in whatever format you specify in format. (See here for the list of formats https://github.com/raysan5/raylib/blob/611e54e67ebbdcc4250719a2e430390eccb72440/src/raylib.h#L775 )

I anticipate your next question will be how to get the raw image data out of opencv image, so I have written an example that does this:

import cv2 as cv
from pyray import *

opencv_image = cv.imread("resources/raylib_logo.jpg")
if opencv_image is None:
    exit("Could not read the image.")

screenWidth = 800
screenHeight = 450
init_window(screenWidth, screenHeight, "example - image loading")

pointer_to_image_data = ffi.from_buffer(opencv_image.data)
raylib_image = Image(pointer_to_image_data, 256, 256, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8)
texture = load_texture_from_image(raylib_image)
unload_image(raylib_image)

while not window_should_close():
    begin_drawing()
    clear_background(RAYWHITE)
    draw_texture(texture, int(screenWidth/2 - texture.width/2), int(screenHeight/2 - texture.height/2), WHITE)
    end_drawing()

unload_texture(texture)
close_window()
madgrizzle commented 2 years ago

Thanks for the quick response! I knew it I had to do something with ffi but couldn't figure out what exactly. Works perfectly.