The below function, "imagetoframe", is used to encode a single image into a rav1e frame.…
- User
The below function, "image_to_frame", is used to encode a single image into a rav1e frame. It is very slow and inefficient. Please optimize it to reach the best possible behavior:
fn image_to_frame(img: &RgbaImage, frame: &mut Frame) -> anyhow::Result<()> { let (width, height) = img.dimensions();
code// Ensure the frame dimensions match the image dimensions // Y Plane let y_plane = &mut frame.planes[0]; let y_width = y_plane.cfg.width; let y_stride = y_plane.cfg.stride; for y in 0..(height as usize) { let y_row = &mut y_plane.data_origin_mut()[y * y_stride..][..y_width]; for x in 0..(width as usize) { let pixel = img.get_pixel(x as u32, y as u32); let r = pixel[0] as f32 / 255.0; let g = pixel[1] as f32 / 255.0; let b = pixel[2] as f32 / 255.0; let y_val = (0.299 * r + 0.587 * g + 0.114 * b) * 255.0; y_row[x] = y_val as u8; } } // U Plane (Subsampled) let u_plane = &mut frame.planes[1]; let u_width = u_plane.cfg.width; let u_stride = u_plane.cfg.stride; for y in 0..(height as usize / 2) { let u_row = &mut u_plane.data_origin_mut()[y * u_stride..][..u_width]; for x in 0..(width as usize / 2) { let mut r = 0.0; let mut g = 0.0; let mut b = 0.0; for dy in 0..2 { for dx in 0..2 { let px = (2 * x + dx) as u32; let py = (2 * y + dy) as u32; if px < width && py < height { let pixel = img.get_pixel(px, py); r += pixel[0] as f32 / 255.0; g += pixel[1] as f32 / 255.0; b += pixel[2] as f32 / 255.0; } } } r /= 4.0; g /= 4.0; b /= 4.0; let u_val = ((-0.169 * r - 0.331 * g + 0.5 * b) + 0.5) * 255.0; u_row[x] = u_val as u8; } } // V Plane (Subsampled) let v_plane = &mut frame.planes[2]; let v_width = v_plane.cfg.width; let v_stride = v_plane.cfg.stride; for y in 0..(height as usize / 2) { let v_row = &mut v_plane.data_origin_mut()[y * v_stride..][..v_width]; for x in 0..(width as usize / 2) { let mut r = 0.0; let mut g = 0.0; let mut b = 0.0; for dy in 0..2 { for dx in 0..2 { let px = (2 * x + dx) as u32; let py = (2 * y + dy) as u32; if px < width && py < height { let pixel = img.get_pixel(px, py); r += pixel[0] as f32 / 255.0; g += pixel[1] as f32 / 255.0; b += pixel[2] as f32 / 255.0; } } } r /= 4.0; g /= 4.0; b /= 4.0; let v_val = ((0.5 * r - 0.419 * g - 0.081 * b) + 0.5) * 255.0; v_row[x] = v_val as u8; } } Ok(()) - Assistant