一、图片校正实现
部分代码
if len(contours2) == 4:
c4 = contours2.reshape(4, 2)
if fclock[0]:
print
"c4=", c4
c4list = c4.tolist()
c4list.reverse()
c4 = np.array(c4list)
c5 = np.zeros((4, 2), dtype=np.float32)
minx = 99999
minindex = 0
for i in range(0, len(c4)):
temp = c4[i, 0] ** 2 + c4[i, 1] ** 2
if minx > temp:
minx = temp
minindex = i
for i in range(0, 4):
c5[i] = c4[minindex]
minindex = minindex + 1
if minindex == 4:
minindex = 0
height = math.sqrt((c5[0, 0] - c5[1, 0]) ** 2 + (c5[0, 1] - c5[1, 1]) ** 2)
height1 = math.sqrt((c5[2, 0] - c5[3, 0]) ** 2 + (c5[2, 1] - c5[3, 1]) ** 2)
if height < height1:
height = height1
width = math.sqrt((c5[0, 0] - c5[3, 0]) ** 2 + (c5[0, 1] - c5[3, 1]) ** 2)
width1 = math.sqrt((c5[2, 0] - c5[1, 0]) ** 2 + (c5[2, 1] - c5[1, 1]) ** 2)
if width < width1:
width = width1
c2 = np.zeros((4, 2), dtype=np.float32)
c2[1] = [0, height]
c2[2] = [width, height]
c2[3] = [width, 0]
c2[0] = [0, 0]
transmtx = cv2.getPerspectiveTransform(c5, c2)
newim = np.zeros((np.int0(width), np.int0(height), 3), np.uint8)
newim = cv2.warpPerspective(
src, transmtx, (np.int0(width), np.int0(height)), newim)
cv2.imshow("5", newim)
cv2.imwrite("output6.jpg",newim)
end = time.time()
print(str(end - start))
black = np.zeros(img.shape, np.uint8)
for i in range(0, 4):
cv2.circle(black, (int(c5[i, 0]), int(c5[i, 1])), 3, (128), 2)
cv2.circle(black, (int(c2[i, 0]), int(c2[i, 1])), 3, (255), 2)
cv2.putText(black, str(i), (int(c5[i, 0]), int(c5[i, 1])),
cv2.FONT_HERSHEY_TRIPLEX, 0.8, (128))
cv2.putText(black, str(i), (int(c2[i, 0]), int(c2[i, 1])),
cv2.FONT_HERSHEY_TRIPLEX, 0.8, (255))
cv2.waitKey(0)
cv2.destroyAllWindows()
二、效果测试
部分校正样例:
1
2
3
4
结果:
1
2
3
4
总结
基本实现了矫正功能以及与后续代码的整合,测试效果时考虑了阴影与折叠等因素,经过调参后可以得到较理想的结果。
缺点与改进:1、只以四个角为基准透视变换可能导致后续单个方格识别准确率降低 2、准备对图片的像素和比例做一定的规范处理方便后续识别
后续工作:搭建以SpringBoot为框架的java后端