需要安装扩展库 opencv-contrib-python
CV_class.py
import cv2
import numpy as np
#import serial
import os,sys
from datetime import datetime
import _thread
import threadingimport timeimport win32ui#只有windows能用.
#from CV_class import *def p(x=""):print(x)
def pt(x="",x1=None):p(f" {x} :{type(x1)}>{x1}")
def pf(x):for i in x:p(f"{i}")
def cmd(s="pause"):os.system(s)def thread_it(func, *args):#传入函数名和参数t = threading.Thread(target=func, args=args)t.setDaemon(True)t.start()r"""
import clr
import System
from System import String, Char, Int32,UInt16, Int64, Environment, IntPtr
print(f"{clr.AddReference('System')}")
def tim(x1=1,x2=1):#定时器事件这个函数一定要有且只能有两个参数;否则报错;print(f"定时器事件{time.time()}")def Winform_timer(itimer=500):t = System.Timers.Timer(itimer);t.Elapsed += System.Timers.ElapsedEventHandler(tim);#到达时间的时候执行事件;t.AutoReset = True;#设置是执行一次(false)还是一直执行(true);t.Enabled = True;#是否执行System.Timers.Timer.Elapsed事件;
"""def getfilepath(path=f'{os.getcwd()}'):dlg =win32ui.CreateFileDialog(1)dlg.SetOFNInitialDir(path)dlg.DoModal()filename=dlg.GetPathName();#return filenamedef CV_Getimg(picpath,x2=1):All_Suffix_Name= (".jpg",".JPG",".bmp",".BMP",".png",".PNG")for S in All_Suffix_Name:#检查后缀名RRR=os.path.splitext(picpath)[-1] == f"{S}";if RRR==True:try:#打开一个可以含有中文路径的图片文件.""""""return cv2.imdecode(np.fromfile(picpath,dtype=np.uint8),x2)except:print("不支持打开此图片.")return np.zeros((1,1,1),dtype="uint8")print("不是有效后缀名.")return np.zeros((1,1,1),dtype="uint8")
##result=True;
#用法 img=CV_Getimg(getfilepath())def CV_Saveimg(img,Name=f"{str(datetime.now().strftime('%Y-%m-%d-%H_%M_%S'))}.jpg",path=""):if path!="":#没有检查路径是否合法.path=path+"\\" try:#保存一个可以含有中文路径的图片文件.""""""cv2.imencode('.jpg', img)[1].tofile(f"{path}{Name}")print("Save Done!")return Trueexcept:print("不能保存此图片!")return False
#用法:CV_Saveimg(img,path=rf"{os.getcwd()}\保存的图")def CV_imshow(x1,frame):cv2.namedWindow(x1,flags=cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED)cv2.imshow(x1,frame)return 0def CV_flip(frame, flipCode):## 图片镜像# * 水平翻转 flipCode = 1# * 垂直翻转 flipCode = 0# * 同时水平翻转与垂直翻转 flipCode = -1return cv2.flip(frame, flipCode)def CV_BGR2GRAY(frame):#将BGR彩图变换为灰度图return cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)def TKC2RGB(color='#000000'):return (int(f'0x{color[1:3]}',16),int(f'0x{color[3:5]}',16),int(f'0x{color[5:]}',16))
#TKColor2RGB()
def TKC2BGR(color='#000000'):return (int(f'0x{color[5:]}' , 16),int(f'0x{color[3:5]}', 16),int(f'0x{color[1:3]}', 16))
#TKColor2BGR()def img(picpath="Lena.jpg",x2=1):return CV_Getimg(picpath,x2)def CV_shape(img):i=0for x in img.shape:i=i+1if i==3:rows,cols,ch=img.shapeif i==2:ch=1rows,cols=img.shape"""p(f"像素:{img.shape} 行,列,通道 (512,512,3)")#p(f"像素:{img.size}")p(f"图像的数据类型:{img.dtype}")类型,像素数目,(行,列,通道) """ return img.dtype,img.size,(rows,cols,ch)def SHOW(img,n="img"):cv2.namedWindow(n,flags=cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED)cv2.moveWindow(n,0,0);#不能在循环里面否则会锁住窗口位置 HWT=CV_shape(img)cv2.resizeWindow(n,200,200)#不能在循环里面,否则会锁住窗口大小.while(1):cv2.imshow(n,img)if cv2.waitKey(1)&0xFF==27:#按"ESC|退出键关闭窗口"breakcv2.destroyWindow(n)#关闭自己.
#--------------------------------------------------------------------------
主程序.py
import cv2
import numpy as np
#from matplotlib import pyplot as plt
import copy
from CV_class import *#img = cv2.imread('1.bmp', 0)
img=CV_Getimg(getfilepath(),0)
imgbak=copy.deepcopy(img)#备份图img = cv2.medianBlur(img, 5)#中值滤波medianBlurret, th1 = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)_,thhh=cv2.threshold(img, 254, 255, cv2.THRESH_BINARY)
thhh = cv2.medianBlur(thhh, 5)_,thll=cv2.threshold(img, 0, 1, cv2.THRESH_BINARY)th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)#MEAN
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)#GAUSSIANbitwiseAnd = cv2.bitwise_and(th1, th2)
And23 = cv2.bitwise_and(th2, th3)"""
And23 = cv2.bitwise_and(th2, th3)
bitwiseOr = cv2.bitwise_or(rectangle, circle)
bitwiseXor = cv2.bitwise_xor(rectangle, circle)
bitwiseNot = cv2.bitwise_not(circle)
"""
titles = ['img', 'th1','th2', 'th3',"bitwiseAnd","and23","thhh","thll"]
images = [img, th1, th2, th3,bitwiseAnd,And23,thhh,thll]#for i in range(len(images)):
# plt.subplot(3, 3, i + 1), plt.imshow(images[i], 'gray')
# plt.title(titles[i])
# plt.xticks([]), plt.yticks([])
#plt.show()#cmd()cv2.imshow(titles[0], images[0])
cv2.imshow(titles[1], images[1])
cv2.imshow(titles[2], images[2])
cv2.imshow(titles[3], images[3])
cv2.imshow(titles[4], images[4])
cv2.imshow(titles[5], images[5])cv2.waitKey(0)