У меня есть модель обнаружения полосы движения на основе архитектуры ENET. Я преобразовал его в модель TFLITE.
Перед отправкой изображения в модель мне нужно передать его через операцию изменения размера, уменьшая его до (80, 160, 3). Тем не менее, операции opencv Resempize в Python (работа на ПК) и Android (с использованием DART FFI с OpenCV2) дают неправильные и противоречивые результаты. В то время как imread считывает изображение как Uint8, значения измененного размера значительно различаются между реализациями ПК и Android. float* resizeAndConvertToFloat32(char* inputImagePath, int* outSize) {
Mat img = imread(inputImagePath);
if(img.empty()) {
platform_log("Error: Image could not be read");
*outSize = 0;
return nullptr;
}
cvtColor(img, img, COLOR_BGR2RGB);
Mat resizedImg;
resize(img, resizedImg, Size(160, 80), 0, 0, INTER_LINEAR);
Mat floatImg;
resizedImg.convertTo(floatImg, CV_32F);
int totalSize = floatImg.rows * floatImg.cols * floatImg.channels();
*outSize = totalSize;
float* result = (float*)malloc(totalSize * sizeof(float));
if(floatImg.isContinuous()) {
memcpy(result, floatImg.data, totalSize * sizeof(float));
} else {
int rowSize = floatImg.cols * floatImg.channels();
for(int i = 0; i < floatImg.rows; i++) {
memcpy(result + i * rowSize, floatImg.ptr(i), rowSize * sizeof(float));
}
}
platform_log("Image resized to 160x80x3 and converted to float32 with preserve_range=True. Total elements: %d", totalSize);
return result;
}
< /code>
файл Python: < /p>
import numpy as np
import cv2
import tensorflow as tf
from skimage.transform import resize
def load_tflite_model(model_path):
interpreter = tf.lite.Interpreter("/content/enet_model.tflite")
interpreter.allocate_tensors()
print("Loaded TensorFlow Lite model successfully.")
return interpreter
def predict_tflite(interpreter, input_data):
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print("Input data:", input_data)
#print("Input type:", type(input_data))
#print("Input shape:", input_data.shape)
#print("---------------------------------")
#print("Input details:", input_details)
#print("Output details:", output_details)
#print("Quantization Scale:", input_details[0]['quantization'])
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])*255
#print("Model prediction completed. Output shape:", output_data.shape)
#print(output_data)
return output_data
def road_lines(image, interpreter, lanes):
h, w = image.shape[:2]
image = image.copy()
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
small_img = resize(image, (80, 160), preserve_range=True)
small_img = np.array(small_img, dtype=np.float32)
small_img = small_img[None, :, :, :]
# print("small image", small_img)
#print("Resized image for model input:", small_img.shape)
prediction = predict_tflite(interpreter, small_img)[0]
lanes.recent_fit.append(prediction)
if len(lanes.recent_fit) > 5:
lanes.recent_fit = lanes.recent_fit[1:]
lanes.avg_fit = np.mean(np.array(lanes.recent_fit), axis=0)
#print("lanes recent fit:", lanes.recent_fit)
#print("lanes recent fit,shape:", type(lanes.recent_fit))
print("-------------------------------------------------")
# print("lanes avg fit:", lanes.avg_fit[75])
# print("lanes avg fit,shape:", type(lanes.avg_fit))
print("-------------------------------------------------")
lane_avg_uint8 = np.clip(lanes.avg_fit, 0, 255).astype(np.uint8)
#print("lane uin8", lane_avg_uint8[75])
# print("lane uin8,shape", lane_avg_uint8.shape)
#print("lane uin8,type", type(lane_avg_uint8.shape[0]))
# print("lane uint8 y", lane_avg_uint8[75])
# print("type", type(lane_avg_uint8[75]))
left_boundary = []
right_boundary = []
threshold_boundary = 128
for y in range(lane_avg_uint8.shape[0]):
row = lane_avg_uint8[y]
indices = np.where(row > threshold_boundary)[0]
if indices.size > 0:
left_boundary.append((indices[0], y))
right_boundary.append((indices[-1], y))
print("left boundary", left_boundary)
print("right boundary", right_boundary)
scale_x = w / 160.0
scale_y = h / 80.0
left_boundary_scaled = [(int(x * scale_x), int(y * scale_y)) for (x, y) in left_boundary]
right_boundary_scaled = [(int(x * scale_x), int(y * scale_y)) for (x, y) in right_boundary]
print("left boundary scaled", left_boundary_scaled)
print("right boundary scaled", right_boundary_scaled)
if len(left_boundary_scaled) > 1:
cv2.polylines(image, [np.array(left_boundary_scaled, dtype=np.int32)],
isClosed=False, color=(0, 255, 0), thickness=5)
if len(right_boundary_scaled) > 1:
cv2.polylines(image, [np.array(right_boundary_scaled, dtype=np.int32)],
isClosed=False, color=(0, 255, 0), thickness=5)
left_bottom = left_boundary_scaled[-1] if left_boundary_scaled else None
right_bottom = right_boundary_scaled[-1] if right_boundary_scaled else None
print("Lane detection completed.")
return image
< /code>
Ввод модели: (1,80,160,3)
Выход модели: (1,80,160,1) < /p>
Я понял, что операция изменения размера, используемая в Python, от Skimage. Я читал, что их методы интерполяции могут быть разными, поэтому я сделал их одинаковыми. Я также читал, что Python читает изображения в формате BGR, в то время как OpenCV читает их в RGB, поэтому я гарантировал, что они были одинаковыми. Тем не менее, ни одно из этих изменений не сработало. < /P>
Короче говоря, я полагаю, что я пробовал все возможные решения, но я все еще не получил ожидаемый результат. Там нет проблем с процессом чтения; Оба метода читают изображение одинаково. Однако существует значительная разница в выводе операции изменения размера.import 'dart:ffi';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'dart:io' show Platform, File;
import 'package:tflite_flutter/tflite_flutter.dart';
class OpenCVProcessor {
late final DynamicLibrary _nativeLib;
late final Pointer Function(Pointer, Pointer)
_resizeAndConvert;
late final void Function(Pointer) _freeFloatArray;
static final OpenCVProcessor _instance = OpenCVProcessor._internal();
factory OpenCVProcessor() {
return _instance;
}
OpenCVProcessor._internal() {
_loadLibrary();
}
void _loadLibrary() {
_nativeLib = Platform.isAndroid
? DynamicLibrary.open('libmy_functions.so')
: DynamicLibrary.process();
_resizeAndConvert = _nativeLib
.lookup<
NativeFunction<
Pointer Function(Pointer,
Pointer)>>('resizeAndConvertToFloat32')
.asFunction();
_freeFloatArray = _nativeLib
.lookup('freeFloatArray')
.asFunction();
}
Future processImage(String imagePath) async {
final imagePathPointer = imagePath.toNativeUtf8();
final outSizePointer = calloc();
try {
final resultPointer = _resizeAndConvert(imagePathPointer, outSizePointer);
if (resultPointer == nullptr || outSizePointer.value
Подробнее здесь: https://stackoverflow.com/questions/795 ... -in-python
Android Image Изменение размера разбила работает не так, как в Python ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
EW Изменение размера разбила по вращению прямоугольника в холсте HTML
Anonymous » » в форуме Javascript - 0 Ответы
- 18 Просмотры
-
Последнее сообщение Anonymous
-