python 精明等边缘检测的方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 精明等边缘检测的方法相关的知识,希望对你有一定的参考价值。
import numpy as np
import cv2
def resize_img(filename):
image = cv2.imread(filename)
resized = cv2.resize(image,None,fx=0.125, fy=0.125, interpolation=cv2.INTER_AREA)
cv2.imwrite(filename,resized)
# resize_img("./page_1.jpg")
def canny(filename):
img = cv2.imread(filename,0)
edges = cv2.Canny(img,50,150,apertureSize = 3)
cv2.imshow('edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
return edges
def laplacian(filename):
img = cv2.imread(filename, 0)
gray_lap = cv2.Laplacian(img,cv2.CV_16S,ksize = 3)
dst = cv2.convertScaleAbs(gray_lap)
cv2.imshow('laplacian',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
return dst
def sobel(filename):
img = cv2.imread(filename, 0)
x = cv2.Sobel(img,cv2.CV_16S,1,0)
y = cv2.Sobel(img,cv2.CV_16S,0,1)
absX = cv2.convertScaleAbs(x)# 转回uint8
absY = cv2.convertScaleAbs(y)
dst = cv2.addWeighted(absX,0.5,absY,0.5,0)
cv2.imshow("absX", absX)
cv2.imshow("absY", absY)
cv2.imshow("Result", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
return absX,absY,dst
def holine_img(img):
height,wight=img.shape[:2]
lines_hor = cv2.HoughLines(img,1,np.pi/180,wight*8//10)
for lineone in lines_hor:
for rho,theta in lineone:
a = np.cos(theta)
b = np.sin(theta)
if b==1:
x0 = a*rho
y0 = b*rho
x1 = 0
y1 = int(y0 + 1000*(a))
x2 = wight-1
y2 = int(y0 - 1000*(a))
cv2.line(img,(x1,y1),(x2,y2),(255,25,0),2)
lines_ver = cv2.HoughLines(img,1,np.pi/180,height*8//10)
for lineone in lines_ver:
for rho,theta in lineone:
a = np.cos(theta)
b = np.sin(theta)
if b==0:
x0 = a*rho
y0 = b*rho
x1 = x0
y1 =0
x2 = x0
y2 =height-1
cv2.line(img,(x1,y1),(x2,y2),(0,25,255),2)
cv2.imwrite("houghline_demo.jpg",img)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def corrective_transform(image, pos):
height = image.shape[0]
width = image.shape[1]
# 获取四个点,顺时针获取
left_top = pos[0]
right_top = pos[1]
right_down = pos[2]
left_down = pos[3]
# print('pos:', pos)
dx = width
dy = height
pts1 = np.float32([left_top, right_top, right_down, left_down])
pts2 = np.float32([[0, 0], [dx, 0], [dx, dy], [0, dy]])
# 计算透视变换的矩阵
M = cv2.getPerspectiveTransform(pts1, pts2)
# 透视变换
dst = cv2.warpPerspective(image, M, (int(dx), int(dy)))
return dst
# 结果展示
# savepath = './corrective/' + image_name + '_c.jpg'
# cv2.imwrite(savepath, dst)
img=laplacian("./page_1.jpg")
holine_img(img)
# sobel("./page_1.jpg")
以上是关于python 精明等边缘检测的方法的主要内容,如果未能解决你的问题,请参考以下文章
二进制阈值图像-> 应用精明的边缘检测-> findContour(),这会改善轮廓检测吗?