简体   繁体   中英

Perspective transform using Opencv

I am trying to achieve perspective transformation using Python and Open CV. While the transformation is done by selecting 4 points on the image, the output image is highly blurred. Even when I don't use the mouse event for selecting the 4 points(rather hard coding it), the image quality is still blurred.Here is my programmatic attempt to this:

`def draw_circle(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img, (x, y), 5, (255, 0, 0), -1)
        p = (x, y)
        l.append(p)
        print(l)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
img = cv2.imread('Path  to my input image')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
cv2.resizeWindow('image', 600, 600)

cv2.setMouseCallback('image', draw_circle)

while 1:
    cv2.imshow('image', img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()

rows, cols, channels = img.shape
pts1 = np.float32(l)
pts2 = np.float32([[0, 0], [200, 0], [200, 100], [0, 100]])

M = cv2.getPerspectiveTransform(pts1, pts2)
dst = cv2.warpPerspective(img, M, (200, 100), cv2.INTER_LINEAR)

h1 = math.sqrt((abs(pts1[1][0] - pts1[0][0])) ** 2 + (abs(pts1[1][1] - pts1[0][1])) ** 2)
h2 = math.sqrt((abs(pts1[3][0] - pts1[2][0])) ** 2 + (abs(pts1[3][1] - pts1[2][1])) ** 2)
v1 = math.sqrt((abs(pts1[3][0] - pts1[0][0])) ** 2 + (abs(pts1[3][1] - pts1[0][1])) ** 2)
v2 = math.sqrt((abs(pts1[2][0] - pts1[1][0])) ** 2 + (abs(pts1[2][1] - pts1[1][1])) ** 2)
max_h = int(max(h1, h2))
max_v = int(max(v1, v2))


dst = cv2.resize(dst, (max_h, max_v))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()`

Here is my input image: This is a fridge image with selective beverages

屏幕截图

Here is my output image: This is the output image after perspective transform

屏幕截图

replace in your code this line

pts2 = np.float32([[0, 0], [200, 0], [200, 100], [0, 100]])

to this one (maybe you have to switch v/h order, I don't know python syntax):

pts2 = np.float32([[0, 0], [max_h,0], [max_h,max_v], [0,max_v]])

by moving the max_h/max_v computation to before transformation computation. Then remove the resizing code.

At the moment you first (implicitly) resize to a 100x200 temporary image, which will be very blurry if you resize it to a bigger image afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM