void Camera3OutputStream::cropI420(char *src_i420_data, int width, int height, char *dst_i420_data,int dst_width, int dst_height,int left,int top){ //裁剪的区域大小不对 if (left + dst_width > width || top + dst_height > height) { return; } int src_length = width*height*3/2; int dst_i420_y_size = dst_width * dst_height; int dst_i420_u_size = dst_i420_y_size >> 2; unsigned char *dst_i420_y_data = (unsigned char*)dst_i420_data; unsigned char *dst_i420_u_data = (unsigned char*)dst_i420_data + dst_i420_y_size; unsigned char *dst_i420_v_data = (unsigned char*)dst_i420_data + dst_i420_y_size + dst_i420_u_size; libyuv::ConvertToI420((const uint8 *)(src_i420_data), src_length, (uint8 *) (dst_i420_y_data), dst_width, (uint8 *) (dst_i420_u_data), dst_width >> 1, (uint8 *) (dst_i420_v_data), dst_width >> 1, left, top, width, height, dst_width, dst_height, libyuv::kRotate0, libyuv::FOURCC_I420); }帮忙优化一下这个代码
时间: 2023-12-14 08:37:30 浏览: 102
simple_char.rar_java 聊天室
下面是优化后的代码,主要是添加了一些错误检查和优化了内存拷贝操作:
```cpp
void Camera3OutputStream::cropI420(char *src_i420_data, int width, int height, char *dst_i420_data, int dst_width, int dst_height, int left, int top) {
if (left < 0 || top < 0 || dst_width <= 0 || dst_height <= 0) {
return;
}
int right = left + dst_width;
int bottom = top + dst_height;
if (right > width || bottom > height) {
return;
}
int src_y_size = width * height;
int src_uv_size = src_y_size / 4;
int dst_y_size = dst_width * dst_height;
int dst_uv_size = dst_y_size / 4;
unsigned char *src_y_data = (unsigned char *)src_i420_data;
unsigned char *src_u_data = (unsigned char *)src_i420_data + src_y_size;
unsigned char *src_v_data = (unsigned char *)src_i420_data + src_y_size + src_uv_size;
unsigned char *dst_y_data = (unsigned char *)dst_i420_data;
unsigned char *dst_u_data = (unsigned char *)dst_i420_data + dst_y_size;
unsigned char *dst_v_data = (unsigned char *)dst_i420_data + dst_y_size + dst_uv_size;
for (int i = 0; i < dst_height; i++) {
memcpy(dst_y_data + i * dst_width, src_y_data + (top + i) * width + left, dst_width);
}
for (int i = 0; i < dst_height / 2; i++) {
memcpy(dst_u_data + i * dst_width / 2, src_u_data + ((top + i * 2) * width + left) / 2, dst_width / 2);
memcpy(dst_v_data + i * dst_width / 2, src_v_data + ((top + i * 2) * width + left) / 2, dst_width / 2);
}
}
```
优化后的代码先进行了一些错误检查,确保裁剪区域在原始图像范围内,同时目标图像的宽度和高度也必须大于0。然后计算出各个数据区域的大小和指针,使用 `memcpy` 函数进行内存拷贝操作。这种方式比使用 libyuv 库中的 `ConvertToI420` 函数更加高效,因为它避免了重复的内存分配和拷贝操作。
阅读全文