opencv 自适应阈值

需要安装扩展库 opencv-contrib-python

CV_class.py

python 复制代码
import cv2
import numpy as np
#import serial
import os,sys
from datetime import datetime
import _thread
import threading





import time


import 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 filename


def 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 True
    except:
        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 0
    
    
    
def CV_flip(frame, flipCode):
    ## 图片镜像
    # * 水平翻转 flipCode = 1
    # * 垂直翻转 flipCode = 0
    # * 同时水平翻转与垂直翻转 flipCode = -1
    return 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=0
    for x in img.shape:
        i=i+1
    if i==3:
        rows,cols,ch=img.shape
    if i==2:
        ch=1
        rows,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|退出键关闭窗口"
            break
    cv2.destroyWindow(n)#关闭自己.      
#--------------------------------------------------------------------------



    
    
    
    
    
    
    
      

主程序.py

python 复制代码
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)#中值滤波medianBlur

ret, 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)#GAUSSIAN

bitwiseAnd = 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)
相关推荐
Felaim7 分钟前
基于模仿学习(IL)的端到端自动驾驶发展路径
人工智能·深度学习·自动驾驶
苦学LCP的小猪1 小时前
OpenCV图像基本操作
opencv·计算机视觉
量子-Alex1 小时前
【目标检测】【PANet】Path Aggregation Network for Instance Segmentation
人工智能·目标检测·计算机视觉
lihuayong1 小时前
计算机视觉:经典数据格式(VOC、YOLO、COCO)解析与转换(附代码)
人工智能·yolo·目标检测·计算机视觉·目标跟踪·coco·数据标注
thinkMoreAndDoMore1 小时前
深度学习(3)-TensorFlow入门(常数张量和变量)
开发语言·人工智能·python
神舟之光1 小时前
动手学深度学习2025.2.23-预备知识之-线性代数
人工智能·深度学习·线性代数
wapicn991 小时前
‌挖数据平台对接DeepSeek推出一键云端部署功能:API接口驱动金融、汽车等行业智能化升级
java·人工智能·python·金融·汽车·php
不爱学习的YY酱1 小时前
MusicGPT的本地化部署与远程调用:让你的Windows电脑成为AI音乐工作站
人工智能·windows
kakaZhui1 小时前
【多模态大模型】端侧语音大模型minicpm-o:手机上的 GPT-4o 级多模态大模型
人工智能·chatgpt·aigc·llama
艾思科蓝 AiScholar1 小时前
【SPIE出版,见刊快速,EI检索稳定,浙江水利水电学院主办】2025年物理学与量子计算国际学术会议(ICPQC 2025)
图像处理·人工智能·信息可视化·自然语言处理·数据分析·力扣·量子计算