8/2/2023 0 Comments Pil image resize aspect ratio![]() CHAIN_APPROX_SIMPLE ) print ( "Number of objects detected:", len (contours ) ) # define function to compute aspect ratio def aspect_ratio (cnt ) :Ĭnt = contours # find the aspect ratioĪr = aspect_ratio (cnt ) # round it to two decimal pointsĬv2. threshold (gray, 150, 255, 0 ) # find the contoursĬontours ,hierarchy = cv2. COLOR_BGR2GRAY ) # apply thresholding to convert grayscale to binary image imread ( 'fourpoint-star.png' ) # convert the image to grayscale We also put the aspect ratio as text for the object. We draw the contour and bounding rectangle for the object on the image. In this Python program, we compute the aspect ratio of an object in the image. Let's have a look at some examples for more clear understanding. Print the aspect ratio and display the image with the drawn contours, bounding rectangle. Optionally you can draw the contours and bounding rectangle on the input image. Compute the aspect ratio using width and height of the bounding rectangle of the object. ![]() Select a contour cnt or loop over all contours. contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ret,thresh = cv2.threshold(gray,150,255,0)įind the contours in the image using cv2.findContours() function. Adjust the second argument for better detection of contour. Gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)Īpply thresholding on the grayscale image to create a binary image. Read the input image using cv2.imread() and convert it to grayscale. In all the following Python examples, the required Python library is OpenCV. You can use the following steps to compute aspect ratio of an object in an image − Here, " cnt" is a numpy array of the contour points of an object in the image. Syntax x, y, w, h = cv2.boundingRect(cnt) We use the width and height to compute the aspect ratio. It accepts the contour points of the object and returns top-left coordinate (x,y) and ( width, height) of the bounding rectangle. Bounding rectangle of an object can be found using cv2.boundingRect() function. So, to compute the aspect ratio, we first have to find the bounding rectangle of the object. The aspect ratio of an object is computed as the ratio between the width and height of the bounding rectangle of the object.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |