1616
1717// Default webcam device
1818#define VIDEO_DEVICE "/dev/video0"
19- #define WIDTH 240
20- #define HEIGHT 240
19+ #define CAPTURE_WIDTH 640 // Capture at 640x480
20+ #define CAPTURE_HEIGHT 480
21+ #define OUTPUT_WIDTH 240 // Resize to 240x240
22+ #define OUTPUT_HEIGHT 240
2123
2224// Structure to hold webcam state
2325typedef struct {
@@ -67,10 +69,10 @@ static mp_obj_t webcam_capture_grayscale(void) {
6769 mp_raise_OSError (errno );
6870 }
6971
70- // Set format to YUYV
72+ // Set format to YUYV at 640x480
7173 fmt .type = V4L2_BUF_TYPE_VIDEO_CAPTURE ;
72- fmt .fmt .pix .width = WIDTH ;
73- fmt .fmt .pix .height = HEIGHT ;
74+ fmt .fmt .pix .width = CAPTURE_WIDTH ;
75+ fmt .fmt .pix .height = CAPTURE_HEIGHT ;
7476 fmt .fmt .pix .pixelformat = V4L2_PIX_FMT_YUYV ;
7577 fmt .fmt .pix .field = V4L2_FIELD_ANY ;
7678 if (ioctl (cam .fd , VIDIOC_S_FMT , & fmt ) < 0 ) {
@@ -126,22 +128,35 @@ static mp_obj_t webcam_capture_grayscale(void) {
126128 mp_raise_OSError (errno );
127129 }
128130
129- // Convert YUYV to grayscale
130- size_t grayscale_size = WIDTH * HEIGHT ;
131- uint8_t * grayscale_buf = (uint8_t * )malloc (grayscale_size );
131+ // Convert YUYV to grayscale (640x480)
132+ size_t capture_size = CAPTURE_WIDTH * CAPTURE_HEIGHT ;
133+ uint8_t * grayscale_buf = (uint8_t * )malloc (capture_size );
132134 if (!grayscale_buf ) {
133135 ioctl (cam .fd , VIDIOC_STREAMOFF , & type );
134136 munmap (cam .buffer , cam .buffer_length );
135137 close (cam .fd );
136138 mp_raise_OSError (ENOMEM );
137139 }
138- yuyv_to_grayscale ((uint8_t * )cam .buffer , grayscale_buf , WIDTH , HEIGHT );
140+ yuyv_to_grayscale ((uint8_t * )cam .buffer , grayscale_buf , CAPTURE_WIDTH , CAPTURE_HEIGHT );
141+
142+ // Resize to 240x240
143+ size_t output_size = OUTPUT_WIDTH * OUTPUT_HEIGHT ;
144+ uint8_t * resized_buf = (uint8_t * )malloc (output_size );
145+ if (!resized_buf ) {
146+ free (grayscale_buf );
147+ ioctl (cam .fd , VIDIOC_STREAMOFF , & type );
148+ munmap (cam .buffer , cam .buffer_length );
149+ close (cam .fd );
150+ mp_raise_OSError (ENOMEM );
151+ }
152+ resize_640x480_to_240x240 (grayscale_buf , resized_buf );
153+ free (grayscale_buf ); // Free the 640x480 buffer
139154
140155 // Create MicroPython bytes object
141- mp_obj_t result = mp_obj_new_bytes (grayscale_buf , grayscale_size );
156+ mp_obj_t result = mp_obj_new_bytes (resized_buf , output_size );
142157
143158 // Clean up
144- free (grayscale_buf );
159+ free (resized_buf );
145160 ioctl (cam .fd , VIDIOC_STREAMOFF , & type );
146161 munmap (cam .buffer , cam .buffer_length );
147162 close (cam .fd );
@@ -164,4 +179,3 @@ const mp_obj_module_t webcam_user_cmodule = {
164179
165180// Register the module
166181MP_REGISTER_MODULE (MP_QSTR_webcam , webcam_user_cmodule );
167-
0 commit comments