1、读取图片
# -*- coding: utf-8 -*- """ Created on Tur Jun 5 12:15 2018 @author: gzh """ import numpy as np import cv2 im = cv2.imread('gzh.png') cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image',im) cv2.waitKey(0)
2、二值化 cv2.threshold
import numpy as np import cv2 from matplotlib import pyplot as plt im = cv2.imread('gzh.png') cv2.namedWindow('image', cv2.WINDOW_NORMAL) img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) cv2.imshow('image',img) cv2.waitKey(0) ret,thresh1=cv2.threshold(img,127,255,cv2.THRESH_BINARY) ret,thresh2=cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV) ret,thresh3=cv2.threshold(img,127,255,cv2.THRESH_TRUNC) ret,thresh4=cv2.threshold(img,127,255,cv2.THRESH_TOZERO) ret,thresh5=cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV) titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TPZERO_INV'] images = [img,thresh1,thresh2,thresh3,thresh4,thresh5] for i in xrange(6): plt.subplot(2,3,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.savefig("erzhihua.jpg") plt.show()
先用plt.savefig("文件名")在用plt.show()
不然生成的照片会是一片空白
效果图:
3、提取轮廓点
import numpy as np import cv2 from matplotlib import pyplot as plt im = cv2.imread('gzh.png') imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh=cv2.threshold(imgray,127,255,0) contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #imgray = cv2.drawContours(imgray,contours,3,(0,255,0),3) cv2.drawContours(im,contours,-1,(0,0,255),3) #cv2.namedWindow('img', cv2.WINDOW_NORMAL) cv2.imshow("im",im) cv2.waitKey(0)
效果图: