1 #-*- coding: utf-8 -*-
2 """
3 Created on Tue Sep 17 19:00:45 20194
5 @author: xxr6 """
7 from cv2 import cv2 #因为cv2里面还有cv2 所以要这样干!
8 importnumpy as np9
10 #读取原始图片
11 image= cv2.imread('shuibiao.jpg')12
13 #读入一张白色的图
14 image2=cv2.imread('white.png')15 image3=image216
17 #图片的缩小,记住比例 的缩放
18 r = 500.0 / image.shape[1]19 dim = (500, int(image.shape[0] *r))20 image = cv2.resize(image, dim, interpolation =cv2.INTER_AREA)21 image2=cv2.resize(image2, dim, interpolation =cv2.INTER_AREA)22
23 #图像灰度化处理
24 grayImage =cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)25 #基于Canny的边沿检测(生成的也是二值图)
26 canny=cv2.Canny(grayImage,30,180)27 #cv2.imshow("canny_image",canny)
28 #再canny处理图像以后 用hough直线检测
29 #统计概率霍夫线变换
30
31
32 #步长 阈值 最小直线长度 最大构成直线的点的间隔
33 lines = cv2.HoughLinesP(canny, 1, np.pi / 180, 60, minLineLength=30, maxLineGap=8)34 for line inlines:35 x1, y1, x2, y2 =line[0]36 cv2.line(image2, (x1, y1), (x2, y2), (0, 0, 255), 1)37
38
39
40 #这里进行矩形的轮廓检测 !!!应该找 白色的矩形框
41 image2 =cv2.cvtColor(image2,cv2.COLOR_BGR2GRAY)42 #黑白颜色颠倒
43 height, width =image2.shape44 dst = np.zeros((height,width,1), np.uint8)45 for i inrange(0, height):46 for j inrange(0, width):47 grayPixel =image2[i, j]48 dst[i, j] = 255-grayPixel49
50
51 #高斯滤波(使图像模糊,平滑)
52 #dst=cv2.GaussianBlur(dst,(7,7),0)
53
54 cv2.imshow('dst', dst)55 contours, hierarchy =cv2.findContours(dst,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)56
57 ##绘制直线
58 #max=0
59 #max_i=0
60 #print(len(contours[2]))
61 #for i in range(len(contours)):
62 #if(5==len(contours[i])):
63 #max_i=i
64 #cv2.drawContours(image3,contours,-1,(0,255,255),3)
65 #cv2.imshow("draw_img0", image3)
66
67 ##绘制矩形
68 #for i in range(0,len(contours)):
69 #x, y, w, h = cv2.boundingRect(contours[i])
70 #cv2.rectangle(image3, (x,y), (x+w,y+h), (153,153,0), 5)
71 #cv2.imshow("draw_img0", image3)
72
73 #打印矩形
74 #for i in range(0,len(contours)):
75 #x, y, w, h = cv2.boundingRect(contours[i])
76 #print(contours[0])
77 #cv2.rectangle(image3, (x,y), (x+w,y+h), (255,153,0), 5)
78
79 #标准霍夫线变换(但在这里不太实用)
80 #lines = cv2.HoughLines(canny, 1, np.pi/180, 150)
81 #for line in lines:
82 #rho, theta = line[0] #line[0]存储的是点到直线的极径和极角,其中极角是弧度表示的。
83 #a = np.cos(theta) #theta是弧度
84 #b = np.sin(theta)
85 #x0 = a * rho #代表x = r * cos(theta)
86 #y0 = b * rho #代表y = r * sin(theta)
87 #x1 = int(x0 + 1000 * (-b)) #计算直线起点横坐标
88 #y1 = int(y0 + 1000 * a) #计算起始起点纵坐标
89 #x2 = int(x0 - 1000 * (-b)) #计算直线终点横坐标
90 #y2 = int(y0 - 1000 * a) #计算直线终点纵坐标 注:这里的数值1000给出了画出的线段长度范围大小,数值越小,画出的线段越短,数值越大,画出的线段越长
91 #cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) #点的坐标必须是元组,不能是列表。
92 #cv2.imshow("image-lines", image)
93
94 #二值化图片
95 ##自适应阈值化能够根据图像不同区域亮度分布,改变阈值
96 ##threshold_pic = cv2.adaptiveThreshold(grayImage, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 25, 10)
97 #ret,threshold_pic=cv2.threshold(grayImage,127, 255, cv2.THRESH_BINARY)
98 #cv2.imshow("threshold_image",threshold_pic)
99 #等待显示(不添加这两行将会报错)
100 cv2.waitKey(0)101 cv2.destroyAllWindows()