0

I will bring an example I have a picture of a swimming pool with some tracks I want to take only the three middle tracks Now what is the best way to cut the image in a trapeze shape then how to take this trapeze and try to fit it to the size of the window that will have a relatively similar ratio between the two sides (upper and lower)

image for the example

yoel
  • 1
  • 1

2 Answers2

0

You can use imutils.four_point_transform function. You can read more about it here.

Basic usage is finding the document contours on a canny edge detected image (again, you can use imutils package that I linked), find the contours on that image and then apply four_point_transform on that contour.

EDIT: How to use canny edge detection and four_point_transform

For finding contours you can use openCV and imutils like this:

cnts = cv2.findContours(edged_image.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

Now, when you have the contours just iterate through and see which one is the biggest and has four points (4 vertices). Then just pass the image and the contour to the four_point_transform function like this:

image_2 = four_point_transform(image, biggest_contour)

That's it.

Novak
  • 2,143
  • 1
  • 12
  • 22
  • I would be happy if you could explain a little more in detail how to find the contours by canny detection , because if i use only the four_point_transform without the contours the quality of the image is very low – yoel Jan 03 '19 at 08:12
0

I modified this example

Result:

enter image description here

import numpy as np 
import cv2

# load image
img = cv2.imread('pool.jpg')
# resize to easily fit on screen
img = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
# determine cornerpoints of the region of interest
pts1 = np.float32([[400,30],[620,30],[50,700],[1000,700]])
# provide new coordinates of cornerpoints
pts2 = np.float32([[0,0],[300,0],[0,600],[300,600]])

# determine transformationmatrix
M = cv2.getPerspectiveTransform(pts1,pts2)
# apply transformationmatrix
dst = cv2.warpPerspective(img,M,(300,600))

# display image
cv2.imshow("img", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

Note the rezise function, you may wish to delete that line, but you will have to change the coordinates of the cornerpoints accordingly. I used about the height and width of the base of the trapezoid for the new image (300,600).

You can tweak the cornerpoints and final image size as you see fit.

J.D.
  • 4,511
  • 2
  • 7
  • 20
  • Thank you very much for the answer but the quality of the image is very low, do you have any other idea ? – yoel Jan 03 '19 at 08:13
  • The problem is the image itself. If you zoom in on the top of the image, it is already quite blurred. Those pixels are at the top of the trapezoid and get stretched to make the new image a rectangle. The way to improve the final result is to take a sharp picture with more pixels. – J.D. Jan 03 '19 at 10:09