Drawing a rectangle around all contours in OpenCV Python





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















i have a code which identifies contours after applying filters on video frames. Now in my case i get 3 contours and i show them by drawing rectangles around them, what i want to do is drawing a rectangle around all these 3 contour rectangles. like it will be a larger rectangle, containing 3 detected rectangles.
Here's my simple code of detecting and drawing rectangles around contours.



im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy =

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
(x,y,w,h) = cv2.boundingRect(contour)
if w > 80 and h > 80:
cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('Motion Detector',frame)









share|improve this question

























  • What have you tried? Take a piece of paper and draw it yourself and then think about the algorithm you used.

    – Dan Mašek
    Oct 23 '16 at 14:32













  • Did you try to create one point set from all contours and calculate the boundingRect on that set? Maybe this works.

    – PSchn
    Oct 23 '16 at 19:21


















1















i have a code which identifies contours after applying filters on video frames. Now in my case i get 3 contours and i show them by drawing rectangles around them, what i want to do is drawing a rectangle around all these 3 contour rectangles. like it will be a larger rectangle, containing 3 detected rectangles.
Here's my simple code of detecting and drawing rectangles around contours.



im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy =

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
(x,y,w,h) = cv2.boundingRect(contour)
if w > 80 and h > 80:
cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('Motion Detector',frame)









share|improve this question

























  • What have you tried? Take a piece of paper and draw it yourself and then think about the algorithm you used.

    – Dan Mašek
    Oct 23 '16 at 14:32













  • Did you try to create one point set from all contours and calculate the boundingRect on that set? Maybe this works.

    – PSchn
    Oct 23 '16 at 19:21














1












1








1


3






i have a code which identifies contours after applying filters on video frames. Now in my case i get 3 contours and i show them by drawing rectangles around them, what i want to do is drawing a rectangle around all these 3 contour rectangles. like it will be a larger rectangle, containing 3 detected rectangles.
Here's my simple code of detecting and drawing rectangles around contours.



im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy =

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
(x,y,w,h) = cv2.boundingRect(contour)
if w > 80 and h > 80:
cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('Motion Detector',frame)









share|improve this question
















i have a code which identifies contours after applying filters on video frames. Now in my case i get 3 contours and i show them by drawing rectangles around them, what i want to do is drawing a rectangle around all these 3 contour rectangles. like it will be a larger rectangle, containing 3 detected rectangles.
Here's my simple code of detecting and drawing rectangles around contours.



im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy =

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
(x,y,w,h) = cv2.boundingRect(contour)
if w > 80 and h > 80:
cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('Motion Detector',frame)






python python-2.7 opencv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 23 '16 at 14:43









sisanared

2,22811633




2,22811633










asked Oct 23 '16 at 14:20









Moeed KundiMoeed Kundi

18117




18117













  • What have you tried? Take a piece of paper and draw it yourself and then think about the algorithm you used.

    – Dan Mašek
    Oct 23 '16 at 14:32













  • Did you try to create one point set from all contours and calculate the boundingRect on that set? Maybe this works.

    – PSchn
    Oct 23 '16 at 19:21



















  • What have you tried? Take a piece of paper and draw it yourself and then think about the algorithm you used.

    – Dan Mašek
    Oct 23 '16 at 14:32













  • Did you try to create one point set from all contours and calculate the boundingRect on that set? Maybe this works.

    – PSchn
    Oct 23 '16 at 19:21

















What have you tried? Take a piece of paper and draw it yourself and then think about the algorithm you used.

– Dan Mašek
Oct 23 '16 at 14:32







What have you tried? Take a piece of paper and draw it yourself and then think about the algorithm you used.

– Dan Mašek
Oct 23 '16 at 14:32















Did you try to create one point set from all contours and calculate the boundingRect on that set? Maybe this works.

– PSchn
Oct 23 '16 at 19:21





Did you try to create one point set from all contours and calculate the boundingRect on that set? Maybe this works.

– PSchn
Oct 23 '16 at 19:21












2 Answers
2






active

oldest

votes


















7














Maybe try something like this:



im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy =

height, width, _ = canny_img.shape
min_x, min_y = width, height
max_x = max_y = 0

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
(x,y,w,h) = cv2.boundingRect(contour)
min_x, max_x = min(x, min_x), max(x+w, max_x)
min_y, max_y = min(y, min_y), max(y+h, max_y)
if w > 80 and h > 80:
cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

if max_x - min_x > 0 and max_y - min_y > 0:
cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)


Essentially you want to keep track of what the smallest x and y coordinates are and what the largest x and y coordinates (including the width and height) are, and then just draw a rectangle with those coordinates.






share|improve this answer































    0














    Using numpy:



    boxes = 
    for c in cnts:
    (x, y, w, h) = cv2.boundingRect(c)
    boxes.append([x,y, x+w,y+h])

    boxes = np.asarray(boxes)
    # need an extra "min/max" for contours outside the frame
    left = np.min(boxes[:,0])
    top = np.min(boxes[:,1])
    right = np.max(boxes[:,2])
    bottom = np.max(boxes[:,3])

    cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)





    share|improve this answer


























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40203932%2fdrawing-a-rectangle-around-all-contours-in-opencv-python%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      7














      Maybe try something like this:



      im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

      try: hierarchy = hierarchy[0]
      except: hierarchy =

      height, width, _ = canny_img.shape
      min_x, min_y = width, height
      max_x = max_y = 0

      # computes the bounding box for the contour, and draws it on the frame,
      for contour, hier in zip(contours, hierarchy):
      (x,y,w,h) = cv2.boundingRect(contour)
      min_x, max_x = min(x, min_x), max(x+w, max_x)
      min_y, max_y = min(y, min_y), max(y+h, max_y)
      if w > 80 and h > 80:
      cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

      if max_x - min_x > 0 and max_y - min_y > 0:
      cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)


      Essentially you want to keep track of what the smallest x and y coordinates are and what the largest x and y coordinates (including the width and height) are, and then just draw a rectangle with those coordinates.






      share|improve this answer




























        7














        Maybe try something like this:



        im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

        try: hierarchy = hierarchy[0]
        except: hierarchy =

        height, width, _ = canny_img.shape
        min_x, min_y = width, height
        max_x = max_y = 0

        # computes the bounding box for the contour, and draws it on the frame,
        for contour, hier in zip(contours, hierarchy):
        (x,y,w,h) = cv2.boundingRect(contour)
        min_x, max_x = min(x, min_x), max(x+w, max_x)
        min_y, max_y = min(y, min_y), max(y+h, max_y)
        if w > 80 and h > 80:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

        if max_x - min_x > 0 and max_y - min_y > 0:
        cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)


        Essentially you want to keep track of what the smallest x and y coordinates are and what the largest x and y coordinates (including the width and height) are, and then just draw a rectangle with those coordinates.






        share|improve this answer


























          7












          7








          7







          Maybe try something like this:



          im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

          try: hierarchy = hierarchy[0]
          except: hierarchy =

          height, width, _ = canny_img.shape
          min_x, min_y = width, height
          max_x = max_y = 0

          # computes the bounding box for the contour, and draws it on the frame,
          for contour, hier in zip(contours, hierarchy):
          (x,y,w,h) = cv2.boundingRect(contour)
          min_x, max_x = min(x, min_x), max(x+w, max_x)
          min_y, max_y = min(y, min_y), max(y+h, max_y)
          if w > 80 and h > 80:
          cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

          if max_x - min_x > 0 and max_y - min_y > 0:
          cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)


          Essentially you want to keep track of what the smallest x and y coordinates are and what the largest x and y coordinates (including the width and height) are, and then just draw a rectangle with those coordinates.






          share|improve this answer













          Maybe try something like this:



          im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

          try: hierarchy = hierarchy[0]
          except: hierarchy =

          height, width, _ = canny_img.shape
          min_x, min_y = width, height
          max_x = max_y = 0

          # computes the bounding box for the contour, and draws it on the frame,
          for contour, hier in zip(contours, hierarchy):
          (x,y,w,h) = cv2.boundingRect(contour)
          min_x, max_x = min(x, min_x), max(x+w, max_x)
          min_y, max_y = min(y, min_y), max(y+h, max_y)
          if w > 80 and h > 80:
          cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

          if max_x - min_x > 0 and max_y - min_y > 0:
          cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)


          Essentially you want to keep track of what the smallest x and y coordinates are and what the largest x and y coordinates (including the width and height) are, and then just draw a rectangle with those coordinates.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 23 '16 at 14:55









          pzppzp

          4,9641832




          4,9641832

























              0














              Using numpy:



              boxes = 
              for c in cnts:
              (x, y, w, h) = cv2.boundingRect(c)
              boxes.append([x,y, x+w,y+h])

              boxes = np.asarray(boxes)
              # need an extra "min/max" for contours outside the frame
              left = np.min(boxes[:,0])
              top = np.min(boxes[:,1])
              right = np.max(boxes[:,2])
              bottom = np.max(boxes[:,3])

              cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)





              share|improve this answer






























                0














                Using numpy:



                boxes = 
                for c in cnts:
                (x, y, w, h) = cv2.boundingRect(c)
                boxes.append([x,y, x+w,y+h])

                boxes = np.asarray(boxes)
                # need an extra "min/max" for contours outside the frame
                left = np.min(boxes[:,0])
                top = np.min(boxes[:,1])
                right = np.max(boxes[:,2])
                bottom = np.max(boxes[:,3])

                cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)





                share|improve this answer




























                  0












                  0








                  0







                  Using numpy:



                  boxes = 
                  for c in cnts:
                  (x, y, w, h) = cv2.boundingRect(c)
                  boxes.append([x,y, x+w,y+h])

                  boxes = np.asarray(boxes)
                  # need an extra "min/max" for contours outside the frame
                  left = np.min(boxes[:,0])
                  top = np.min(boxes[:,1])
                  right = np.max(boxes[:,2])
                  bottom = np.max(boxes[:,3])

                  cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)





                  share|improve this answer















                  Using numpy:



                  boxes = 
                  for c in cnts:
                  (x, y, w, h) = cv2.boundingRect(c)
                  boxes.append([x,y, x+w,y+h])

                  boxes = np.asarray(boxes)
                  # need an extra "min/max" for contours outside the frame
                  left = np.min(boxes[:,0])
                  top = np.min(boxes[:,1])
                  right = np.max(boxes[:,2])
                  bottom = np.max(boxes[:,3])

                  cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 24 '18 at 16:14

























                  answered Nov 24 '18 at 15:50









                  lorenzolorenzo

                  14418




                  14418






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40203932%2fdrawing-a-rectangle-around-all-contours-in-opencv-python%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Academy of Television Arts & Sciences

                      L'Équipe

                      1995 France bombings