Muhammad Naeem Paracha
Muhammad Naeem Paracha

Reputation: 2595

Using Google ML object detection and draw bounding boxes on image on iOS

I am working on google ML object detection app. The functionality of app is like user will capture image and send it server for object detection. from server i am getting the JSON response like:

{
  "payload": [
    {
      "imageObjectDetection": {
        "boundingBox": {
          "normalizedVertices": [
            {
              "x": 0.034553755,
              "y": 0.015524037
            },
            {
              "x": 0.941527,
              "y": 0.9912563
            }
          ]
        },
        "score": 0.9997793
      },
      "displayName": "Salad"
    }
  ]
}

from above response i want to draw clickable bounding boxes on images:

[1]:

Kindly suggest me a framework or library draw selectable bounding box on image.

Upvotes: 1

Views: 711

Answers (1)

Victor Mihaita
Victor Mihaita

Reputation: 26

You don't need any library for this because this is quite a simple process.. Just call this function with the x and y values that you get from api and it should be okay. and of course add the code to the tap gesture


func draxBox(x1: CGFloat, x2: CGFloat, y1: CGFloat, y2: CGFloat) {
    //1. Find the size to the bounding box:
    width = (x2 - x1) * yourImageView.frame.width
    height = (y2 - y1) * yourImageView.frame.height

    //2. Add a subview to yourImageView:
    let boundingBox = UIView()
    boundingBox.backgroundColor = .clear
    boundingBox.layer.borderWidth = 1
    boundingBox.layer.borderColor = UIColor.red.cgColor
    boundingBox.translatesAutoresizingMaskIntoConstraints = false
    yourImageView.addSubview(boundingBox)

    NSLayoutConstraint.activate([
        boundingBox.leadingAnchor.constraint(equalTo: yourImageView.leadingAnchor, constant: x1),
        boundingBox.topAnchor.constraint(equalTo: yourImageView.topAnchor, constant: y1),
        boundingBox.widthAnchor.constraint(equalToConstant: width),
        boundingBox.heightAnchor.constraint(equalToConstant: height)
    ])

    //3. Add tap action to this view:
    let tap = UITapGestureRecognizer(target: self, action: #selector(boxTapped))
    boundingBox.isUserInteractionEnabled = true
    boundingBox.addGestureRecognizer(tap)
}

@objc private fun boxTapped() {
   //actian when tapped goes here
}

Upvotes: 1

Related Questions