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)
相关推荐
lijianhua_97122 小时前
国内某顶级大学内部用的ai自动生成论文的提示词
人工智能
EDPJ3 小时前
当图像与文本 “各说各话” —— CLIP 中的模态鸿沟与对象偏向
深度学习·计算机视觉
蔡俊锋3 小时前
用AI实现乐高式大型可插拔系统的技术方案
人工智能·ai工程·ai原子能力·ai乐高工程
自然语3 小时前
人工智能之数字生命 认知架构白皮书 第7章
人工智能·架构
大熊背3 小时前
利用ISP离线模式进行分块LSC校正的方法
人工智能·算法·机器学习
eastyuxiao3 小时前
如何在不同的机器上运行多个OpenClaw实例?
人工智能·git·架构·github·php
诸葛务农3 小时前
AGI 主要技术路径及核心技术:归一融合及未来之路5
大数据·人工智能
光影少年3 小时前
AI Agent智能体开发
人工智能·aigc·ai编程
charlee443 小时前
最小二乘问题详解17:SFM仿真数据生成
c++·计算机视觉·sfm·数字摄影测量·无人机航测
ai生成式引擎优化技术3 小时前
TSPR-WEB-LLM-HIC (TWLH四元结构)AI生成式引擎(GEO)技术白皮书
人工智能