ra1nty / DXcam

A Python high-performance screen capture library for Windows using Desktop Duplication API
MIT License
457 stars 67 forks source link

[NOT-ISSUE] [TUTORIAL] Adding Cursor To Screen Capture #81

Open elmoiv opened 5 months ago

elmoiv commented 5 months ago

For those wondering how to show cursor on screen capture:

FPS = 60 DURATION = 30 RESOLUTION = dxcam.__factory.outputs[0][0].resolution

cursoricon = \ b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 ' + \ b'\x08\x03\x00\x00\x00D\xa4\x8a\xc6\x00\x00\x003PLTE\x00\x00\x00' + \ b'\x01\x02\x10\x00\x01\x0e\x02\x05\x16\x00\x01\x0f\x00\x00\x0e\x01' + \ b'\x02\x11\x02\x04\x15\x01\x02\x12\x03\x05\x18\xff\xff\xff\xf5\xf5' + \ b'\xf8\xe1\xe1\xe3\xd6\xd6\xd8\xe8\xe8\xea\xc2\xc2\xc9\xb3\xb4\xbc' + \ b'\xbc\xcdR^\x00\x00\x00\ntRNS\x00\xbd\xe76\xd3\xf4\xb4M\x9e\x1aY' + \ b'\xc1\x82\x1e\x00\x00\x00fIDAT8\xcb\xed\xcf1\x0e\x800\x0cC\xd1\x84' + \ b'\x94\x02n\x0b\xdc\xff\xb4x\xea\x163#\xf1W?E\x8a-a\xba\xc5\xe3\x05' + \ b'\x80B\x03\n\r\xb4 \xd0\x82@\x0b\x82)$h\x1e\x02L\xa1\x00N\x0f\r\xd0=' + \ b'\x05\rp\x96\x82\xb6\xde\xf0-\xfd\x82{\x14\xf4\x92\x02\xeeV/\xd4\xec' + \ b'\x84s7\x9e\x18\xc5Tu@\x83\xa3\xeca\x7f\xef\x01\xd5h\x03\xe1\xc1\xcc' + \ b'\xc3\xc0\x00\x00\x00\x00IEND\xaeB`\x82'

def cvimg_from_bytestring(raw_data): nparr = np.frombuffer(raw_data, np.uint8) return cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)

def overlay_transparent(background, overlay, x, y): background_width = background.shape[1] background_height = background.shape[0]

if x >= background_width or y >= background_height:
    return background

h, w = overlay.shape[0], overlay.shape[1]

if x + w > background_width:
    w = background_width - x
    overlay = overlay[:, :w]

if y + h > background_height:
    h = background_height - y
    overlay = overlay[:h]

if overlay.shape[2] < 4:
    overlay = np.concatenate(
        [
            overlay,
            np.ones((overlay.shape[0], overlay.shape[1], 1), dtype = overlay.dtype) * 255
        ],
        axis = 2,
    )

overlay_image = overlay[..., :3]
mask = overlay[..., 3:] / 255.0

background[y:y+h, x:x+w] = (1.0 - mask) * background[y:y+h, x:x+w] + mask * overlay_image

return background

cursor_cv2 = cvimg_from_bytestring(cursor_icon)

camera = dxcam.create(output_idx=0, output_color="BGR") camera.start(target_fps=FPS, video_mode=True)

writer = cv2.VideoWriter("video.mp4", cv2.VideoWriter_fourcc(*"mp4v"), FPS, RESOLUTION)

for i in range(FPS * DURATION): frame = camera.get_latest_frame() cursor_pos = camera.grab_cursor().PointerPositionInfo.Position cursor_x = cursor_pos.x + 3 cursor_y = cursor_pos.y + 3 frame = overlay_transparent(frame, cursor_cv2, cursor_x, cursor_y) writer.write(frame)

camera.stop() writer.release()

Sharpjackv commented 4 months ago

thank you