import cv2 import numpy as np import math !wget https://media.wired.com/photos/5c5354d391d0df22c1dee493/master/w_1024%2Cc_limit/Backchannel-Lena-Final.jpg img = cv2.imread('Backchannel-Lena-Final.jpg') h, w, c = img.shape print(h, w, c) mat = cv2.getRotationMatrix2D((w / 2, h / 2), 45, 0.5) print(mat) affine_img = cv2.warpAffine(img, mat, (w, h)) cv2.imwrite('data/dst/opencv_affine.jpg', affine_img) import matplotlib.pyplot as plt plt.subplot(211) plt.imshow(affine_img) plt.subplot(212) plt.imshow(img) plt.title('original') plt.show() affine_img_half = cv2.warpAffine(img, mat, (w, h // 2)) cv2.imwrite('data/dst/opencv_affine_half.jpg', affine_img_half) plt.imshow(affine_img_half) plt.show() !wget https://i.stack.imgur.com/4wQjD.jpg checker = '4wQjD.jpg' gray = cv2.imread( checker ) edges = cv2.Canny(gray, 50, 150, apertureSize = 3) cv2.imwrite('edges-50-150.jpg', edges) minLineLength=100 lines = cv2.HoughLinesP(image=edges,rho=1, theta=np.pi/180, threshold=100, lines=np.array([]), minLineLength=minLineLength, maxLineGap=80) a,b,c = lines.shape for i in range(a): x0, y0, x1, y1 = lines[i][0] cv2.line(gray, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA) cv2.imwrite('houghlines5.jpg',gray) break tangent = (y1-y0)/(x0-x1) print(tangent, np.arctan( tangent/np.pi*180 )+90 ) degree = np.arctan( tangent/np.pi*180 )+90 plt.imshow(gray) plt.show() def coords(cv2_image): edges = cv2.Canny(cv2_image, 50, 150, apertureSize = 3) minLineLength=100 lines = cv2.HoughLinesP(image=edges,rho=1, theta=np.pi/180, threshold=100, lines=np.array([]), minLineLength=minLineLength, maxLineGap=20)# 80 return lines[0][0] p0 = np.array((x0, y0)) p1 = np.array((x1, y1)) h, w, c = gray.shape print(h, w, c) degree = - np.arctan( tangent ) /np.pi*180 mean = (p0+p1)/2 mat = cv2.getRotationMatrix2D( tuple(mean.tolist()), degree, 0.5) print( mat ) affine_img = cv2.warpAffine(gray, mat, (w, h)) c = coords( affine_img ) print( c ) plt.imshow(affine_img) plt.show()