по сути, я учусь в приложении из примеров приложений MLKit и других, чтобы обнаруживать объект с помощью обнаружения объектов MLKit и рисовать ограничивающий блок с помощью специального представления. Сначала я работаю и могу обнаружить объект и нарисовать ограничивающий блок, но все же я забыл зафиксировать проект и просто изменил свой код, после чего он не смог обнаружить объект, мне просто интересно, что происходит
Вот мой код 4, на котором я потенциально могу сосредоточиться на проблеме
class GraphicOverlay(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val lock = Any()
var mScale: Float? = null
var mOffsetX: Float? = null
var mOffsetY: Float? = null
private val graphics = ArrayList()
/**
* Base class for a custom graphics objects to be rendered within the graphic overlay.
* The subclass of this can implement the [Graphic.draw] method to define the graphics element,
* and to add the instances of graphic to the overlay using the [GraphicOverlay.add]
* */
abstract class Graphics protected constructor(protected val overlay: GraphicOverlay) {
protected val context: Context = overlay.context
/** Draws the graphic on the supplied canvas. */
abstract fun draw(canvas: Canvas)
fun calculateRect(height: Float, width: Float, boundingBoxT: Rect): RectF {
// for land scape
fun isLandScapeMode(): Boolean {
return overlay.context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
}
fun whenLandScapeModeWidth(): Float {
return when(isLandScapeMode()) {
true -> width
false -> height
}
}
fun whenLandScapeModeHeight(): Float {
return when(isLandScapeMode()) {
true -> height
false -> width
}
}
val scaleX = overlay.width.toFloat() / whenLandScapeModeWidth()
val scaleY = overlay.height.toFloat() / whenLandScapeModeHeight()
val scale = scaleX.coerceAtLeast(scaleY)
overlay.mScale = scale
// Calculate offset (we need to center the overlay on the target)
val offsetX = (overlay.width.toFloat() - ceil(whenLandScapeModeWidth() * scale)) / 2.0f
val offsetY = (overlay.height.toFloat() - ceil(whenLandScapeModeHeight() * scale)) / 2.0f
overlay.mOffsetX = offsetX
overlay.mOffsetY = offsetY
val mappedBox = RectF().apply {
left = boundingBoxT.right * scale + offsetX
top = boundingBoxT.top * scale + offsetY
right = boundingBoxT.left * scale + offsetX
bottom = boundingBoxT.bottom * scale + offsetY
}
return mappedBox
}
}
fun clear() {
synchronized(lock) {
graphics.clear()
}
postInvalidate()
}
fun add(graphic: Graphics) {
synchronized(lock) {
graphics.add(graphic)
}
}
/** Draws the overlay with its associated graphic objects. */
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
synchronized(lock) {
graphics.forEach { it.draw(canvas) }
}
}
}
class ObjectDetectorGraphic(overlay: GraphicOverlay, private val detectedObject : DetectedObject, private val rect: Rect) : Graphics(overlay) {
private val paintFill = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.argb(70, 255, 255, 255)
style = Paint.Style.FILL
}
private val paintStroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.GRAY
style = Paint.Style.STROKE
strokeWidth = 3f
}
override fun draw(canvas: Canvas) {
// val rect = overlay.translateRect(detectedObject.boundingBox)
val rect = calculateRect(
rect.height().toFloat(),
rect.width().toFloat(),
detectedObject.boundingBox
)
canvas.drawRect(rect, paintFill)
canvas.drawRect(rect, paintStroke)
}
}
В таком случае я не знаю, что не так, и все же не знаю, как это отладить, поскольку в логарифмическом анализаторе, похоже, я не могу найти ничего полезного для моего случая.
Я уже рассматриваю этот случай
(Обнаружение объектов MLKit не обнаруживает объекты), но пока не найдено работающего
по сути, я учусь в приложении из примеров приложений MLKit и других, чтобы обнаруживать объект с помощью обнаружения объектов MLKit и рисовать ограничивающий блок с помощью специального представления. Сначала я работаю и могу обнаружить объект и нарисовать ограничивающий блок, но все же я забыл зафиксировать проект и просто изменил свой код, после чего он не смог обнаружить объект, мне просто интересно, что происходит Вот мой код 4, на котором я потенциально могу сосредоточиться на проблеме [list] [*]ScanFragment (вот часть кода фрагмента)
[code]private fun startCamera() { binding.cameraPreviewGraphicOverlay.clear() val rotation = binding.previewView.display.rotation
val cameraSelector = CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build()
[*]ObjectDetectorProcessor [/list] [code]class ObjectDetectorProcessor( private val listener: (MutableList, image: Rect) -> Unit ) : ImageAnalysis.Analyzer {
private val options = ObjectDetectorOptions.Builder() .apply { setDetectorMode(ObjectDetectorOptions.STREAM_MODE) }.build()
private val detector = ObjectDetection.getClient(options) @SuppressLint("UnsafeOptInUsageError") override fun analyze(imageProxy: ImageProxy) { val mediaImage = imageProxy.image ?: kotlin.run { Log.e(TAG, "Error: imageProxy null") imageProxy.close() return }
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) detector.process(image) .addOnSuccessListener {objectList -> listener(objectList, image.mediaImage?.cropRect!!) } .addOnFailureListener { Log.e(TAG, "Error: ${it.message}", it) } } companion object { private const val TAG = "ObjectAnalyser" } } [/code] [list] [*]GraphicOverlay (в качестве пользовательского представления) [/list] [code]class GraphicOverlay(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val lock = Any() var mScale: Float? = null var mOffsetX: Float? = null var mOffsetY: Float? = null private val graphics = ArrayList()
/** * Base class for a custom graphics objects to be rendered within the graphic overlay. * The subclass of this can implement the [Graphic.draw] method to define the graphics element, * and to add the instances of graphic to the overlay using the [GraphicOverlay.add] * */ abstract class Graphics protected constructor(protected val overlay: GraphicOverlay) { protected val context: Context = overlay.context
/** Draws the graphic on the supplied canvas. */ abstract fun draw(canvas: Canvas)
fun calculateRect(height: Float, width: Float, boundingBoxT: Rect): RectF {
// for land scape fun isLandScapeMode(): Boolean { return overlay.context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE }
val scaleX = overlay.width.toFloat() / whenLandScapeModeWidth() val scaleY = overlay.height.toFloat() / whenLandScapeModeHeight() val scale = scaleX.coerceAtLeast(scaleY) overlay.mScale = scale
// Calculate offset (we need to center the overlay on the target) val offsetX = (overlay.width.toFloat() - ceil(whenLandScapeModeWidth() * scale)) / 2.0f val offsetY = (overlay.height.toFloat() - ceil(whenLandScapeModeHeight() * scale)) / 2.0f
} [/code] [list] [*]И, наконец, ObjectDetectorGraphic [/list] [code]class ObjectDetectorGraphic(overlay: GraphicOverlay, private val detectedObject : DetectedObject, private val rect: Rect) : Graphics(overlay) {
private val paintFill = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.argb(70, 255, 255, 255) style = Paint.Style.FILL }
private val paintStroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.GRAY style = Paint.Style.STROKE strokeWidth = 3f }
override fun draw(canvas: Canvas) { // val rect = overlay.translateRect(detectedObject.boundingBox) val rect = calculateRect( rect.height().toFloat(), rect.width().toFloat(), detectedObject.boundingBox ) canvas.drawRect(rect, paintFill) canvas.drawRect(rect, paintStroke) } } [/code] В таком случае я не знаю, что не так, и все же не знаю, как это отладить, поскольку в логарифмическом анализаторе, похоже, я не могу найти ничего полезного для моего случая. Я уже рассматриваю этот случай (Обнаружение объектов MLKit не обнаруживает объекты), но пока не найдено работающего
Я работаю над отсканированным изображением, которое по сути представляет собой рукописное письмо. Моя цель — найти ограничивающие рамки каждой строки на этом изображении. Но ограничивающие рамки не должны перекрывать друг друга.
Входное...
У меня есть изображение, для которого я хотел бы обнаружить края и нарисовать к нему ограничивающую рамку. Моя проблема в том, что мой код Python не рисует ограничивающую рамку, и я не уверен, что это потому, что он не смог ее обнаружить. объекты в...
Я хочу интегрировать OpenCV с YOLOv8 из ultralytics, поэтому я хочу получить координаты ограничивающего прямоугольника из прогноза модели. Как мне это сделать?
from ultralytics import YOLO
import cv2