首页 > 解决方案 > opencv python 到 kotlin 的转换

问题描述

我正在尝试将python中可用的代码转换为我的android项目的kotlin。我为此使用 yolo 文件。

def detect_person(image, confThreshold):
  img = np.copy(image)
  blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
  net.setInput(blob)
  outputs = net.forward(names)
  outputs = np.vstack(outputs)
  H, W = image.shape[:2]
  boxes = []
  confidences = []
  classIDs = []

  for output in outputs:
        scores = output[5:]
        classID = np.argmax(scores)
        confidence = scores[classID]
        if confidence > confThreshold:
            x, y, w, h = output[:4] * np.array([W, H, W, H])
            p0 = int(x - w//2), int(y - h//2)
            p1 = int(x + w//2), int(y + h//2)
            boxes.append([*p0, int(w), int(h)])
            confidences.append(float(confidence))
            classIDs.append(classID)

  indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, confThreshold-0.1)
  
  bboxes = []
  confs = []
  if len(indices) > 0:
     for i in indices.flatten():
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])
            # track only people in image 
            if classIDs[i] == 0:
               x0 = max(0,x)
               y0 = max(0,y)
               x1 = min(x0+w,img.shape[1])
               y1 = min(y0+h, img.shape[0])
            
               bboxes.append([x0,y0,x1,y1])
               confs.append(round(confidences[i],2))
              
  return bboxes,confs

到目前为止,我可以完成到这一步。我不知道这将如何以其他方式工作。这是我检测人的代码。

 fun detectPerson(img: Bitmap) {

        val imgMat = Mat()
        Utils.bitmapToMat(img, imgMat)

        val blob = Dnn.blobFromImage(
            imgMat,
            1.0,
            Size(300.0, 300.0),
            Scalar(104.0, 177.0, 123.0),
            false,
            false
        )

        maskModel?.setInput(blob)

//        todo what is the first parameter here....???
        val outputs = maskModel?.forward()
        val detections = arrayOf(outputs)


        val H = img.height
        val W = img.width

        var boxes = Mat()
        var confidences = Mat()
        var classIDs = Mat()


        for (output in detections) {


        }

    }

以上是正确的。在 python 中,当 new.forward(names) 我得到输出时,这很好。但在 kotlin 中,我返回 MAT。

关于 NMSBoxes,我尝试查看 python 文档。它返回索引。但是,在用于 kotlin 的 OpenCV 中,我们需要将索引作为 NMSBoxes 中的参数传递吗?我该如何解决?

标签: opencvkotlinopencv3.0detection

解决方案


推荐阅读