0

I use this code to find some blobs, and pick the biggest one.

contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
if len(contours) != 0:
    c = max(contours, key=cv2.contourArea)

Now, I would need to change this code in a way so it returns the contour that is in the middle of the frame. (its bounding box covers the center pixel of the image)

I am not able to figure out how to do this except getting the bounding box of all contours with

xbox, ybox, wbox, hbox = cv2.boundingRect(cont)

and then checking that x and y are smaller than the centere, and x+w and y+h aare bigger than the centre. It does not look like a efficient way tough, since there can be up to 500 small controus..

fmw42
  • 46,825
  • 10
  • 62
  • 80
sharkyenergy
  • 3,842
  • 10
  • 46
  • 97
  • 1
    Chceck out [cv2.pointPolygonTest()](https://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#ga1a539e8db2135af2566103705d7a5722) it does exactly what you're asking – DrBwts Dec 12 '22 at 09:32
  • great! thank you very much.. i can replace the key inside the max function with this one, as the one that is in the center will return 1 and all the others 0 or -1.. could you please post it as answer so I can accept it? – sharkyenergy Dec 12 '22 at 09:37
  • Does this answer your question? [Extract most central area in a Binary Image](https://stackoverflow.com/questions/74564868/extract-most-central-area-in-a-binary-image) – Christoph Rackwitz Dec 12 '22 at 09:42

2 Answers2

1

I'd like to suggest this approach, maybe there is a more straightforward one. I'm writing code here, but instead giving a possible algorithm:

  • Iterate over contours and draw each single contour using a mask in a binary mat (b/w and filled)
  • Check if the center pixel (image width/2, image height/2) is equal to 1

That should work.

rok
  • 2,574
  • 3
  • 23
  • 44
  • thank you! for some reason that does not work on my end. it does not draw my contours filled. i guess that there is a hole somewhere, so drawing it filled produces just the contour. but good idea anyway! – sharkyenergy Dec 12 '22 at 09:27
  • that's weird.. can you post the code you are using to draw contours ? Also a sample image. Are you using the right flag in drawcontours to fill it? – rok Dec 12 '22 at 09:35
1

There is a function in OpenCV that will check if a given point is inside a contour (returns a 1), on the boundary (returns a 0) or outside (returns a -1).

cv2.pointPolygonTest()

DrBwts
  • 3,470
  • 6
  • 38
  • 62