版本一:边框识别
给编码后的图片加上像素大小为5*5的边框
下为生成的图片:
方法一:使用canny边缘检测算法,(可加仿射变换校正图形)
import cv2
import numpy as np
import math
def reshape_image(image):#归一化是为了方便观察,可以去掉这步
'''归一化图片尺寸:短边400,长边不超过800,短边400,长边超过800以长边800为主'''
width, height = image.shape[1], image.shape[0]
min_len = width
scale = width * 1.0 / 400
new_width = 400
new_height = int(height / scale)
if new_height > 800:
new_height = 800
scale = height * 1.0 / 800
new_width = int(width / scale)
out = cv2.resize(image, (new_width, new_height))
return out
def find(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# ret, binary = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(gray, 100, 150) #参数为:源图,最低阈值,最高阈值,调整阈值以获得精度不同的轮廓边缘
contour_info = []
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
largest_area = 0
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
if area > largest_area:
largest_area = area
largest_coutour_index = i
x, y, w, h = cv2.boundingRect(contours[largest_coutour_index])
c=sorted(contours,key=cv2.contourArea, reverse=True)[1]
rect = cv2.minAreaRect(c) # 获取包围盒(中心点,宽高,旋转角度)
box = np.int0(cv2.boxPoints(rect))
draw_img = cv2.drawContours(img.copy(), [box], -1, (0, 0, 255), 3)
pixel = int(h/50)
pix=int(w/50)
new = img[y + 2 + pixel:y + h - 2 - pixel, x + 2 + pix:x + w - pix - 2]
return new
def cut(imgpath):
ori_img = cv2.imread(imgpath)
#img = reshape_image(ori_img)
processed_img=find(ori_img)
cv2.imwrite('111111.png',processed_img)
cut('50.png')
拍摄图片:
canny后的图片:
关于canny的参考资料:
https://blog.csdn.net/weixin_43866530/article/details/105010674
仿射变换代码:(不够精确,但还没有找到原因)
def Perspective_transform(box, original_img):#box是四个点坐标
pts1=np.float32(box)
pts2 = np.float32([[0, 0], [300, 0], [0, 300],