python读取图像小工具

一、和图像交互获得图像的坐标和像素值

python 复制代码
import cv2
import numpy as np
import signal
import threading
import time





if __name__ == '__main__':

    img = cv2.imread('XXX',0)#读取图片
    font_face,font_scale,thickness=cv2.FONT_HERSHEY_SIMPLEX,0.5,1
    #鼠标交互
    def mouseHandler(event,x,y,flags,param):
        points = (x,y)
        global imgCopy
        #鼠标左键双击事件
        if event == cv2.EVENT_LBUTTONDBLCLK:
            #拷贝一张与原图像格式相同的新图像
            imgCopy = img.copy()
            #拼接文字
            text = '['+str(x)+','+str(y)+']'+str(img[y,x])
            print(text)
            #读取文字(宽,高),下基线
            (t_w,t_h),baseLine = cv2.getTextSize(text,font_face,font_scale,thickness)
            #在鼠标当前位置的左上角显示文字
            cv2.putText(imgCopy,text,(x-t_w,y),font_face,font_scale,(125,125,125))
            cv2.imshow('win',imgCopy)
        #鼠标移动事件
        elif event == cv2.EVENT_MOUSEMOVE:
            #显示原图片能使文本框消失
            cv2.imshow('win',img)

    cv2.namedWindow('win')
    #窗口与回调函数绑定
    cv2.setMouseCallback('win',mouseHandler)
    cv2.imshow('win',img)
    cv2.waitKey()

二、二值化图像

python 复制代码
import cv2
import numpy as np
import signal
import threading
import time



if __name__ == '__main__':

    img = cv2.imread('path',0)#读取图片
    ret, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    print("threshold value %s" % ret)  #打印阈值,超过阈值显示为白色,低于该阈值显示为黑色
    cv2.imshow("threshold", binary) #显示二值化图像
    cv2.waitKey(0)
    cv2.destroyAllWindows()

批量图像二值化

python 复制代码
import cv2
import numpy as np
import signal
import threading
import time
import os
import sys
import random
import datetime
import argparse

def get_files(path):
    files = []
    for filename in os.listdir(path):
        if os.path.isfile(os.path.join(path, filename)):
            files.append(filename)
    return files


if __name__ == '__main__':

    files_path="XXX"
    #print(files_path)
    image_files = get_files(files_path)
    i=1
    #print(image_files)
    for image_file in image_files:
        image_path=os.path.join(files_path , image_file)
        print(image_path)
        img = cv2.imread(image_path,0)#读取图片
        start_time_init = time.perf_counter()
        ret, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        end_time_init = time.perf_counter()
        elapsed_time_init = (end_time_init - start_time_init)*1000
        print("二值化时间: {} ms".format(elapsed_time_init))
        print("threshold value %s" % ret)  #打印阈值,超过阈值显示为白色,低于该阈值显示为黑色s
        cv2.imwrite(files_path+"/binary/"+str(i)+".png",binary)
        i=i+1

三、区域合并提取最大连通域

python 复制代码
import cv2
import numpy as np
import signal
import threading
import time
import os
import sys
import random
import datetime
import argparse

def get_files(path):
    files = []
    for filename in os.listdir(path):
        if os.path.isfile(os.path.join(path, filename)):
            files.append(filename)
    return files


if __name__ == '__main__':

    #files_path="/home/robot/PaddleOCR-2.6.0/data/OK0828/raw_data/"
    files_path="/home/robot/PaddleOCR-2.6.0/data/829/"
    files_path="/home/robot/PaddleOCR-2.6.0/data/NG0823/"
    #print(files_path)
    image_files = get_files(files_path)
    i=1
    #print(image_files)
    for image_file in image_files:
        image_path=os.path.join(files_path , image_file)
        print(image_path)
        img = cv2.imread(image_path,0)#读取图片
        start_time_init = time.perf_counter()
        ret, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        end_time_init = time.perf_counter()
        elapsed_time_init = (end_time_init - start_time_init)*1000
        print("二值化时间: {} ms".format(elapsed_time_init))
        print("threshold value %s" % ret)  #打印阈值,超过阈值显示为白色,低于该阈值显示为黑色s
        cv2.imwrite(files_path+"/binary/"+str(i)+".png",binary)
        i=i+1
        # cv2.imshow("threshold", binary) #显示二值化图像
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        start_time = time.perf_counter()
        num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary)
        end_time = time.perf_counter()
        elapsed_time = (end_time - start_time)*1000
        print("连通域的时间: {} ms".format(elapsed_time))

        max_area=0
        j=0
        for st in stats[1:]:
            j=j+1
            area=st[4]
            if(max_area<area):
                max_area=area
                index=j
            
        print("index",index)
        print("max_area",max_area)


        #index=index+1
        print('num_labels: ', num_labels)
        labels[labels>0] = 255
        labels = labels.astype(np.uint8)
        # #将一维灰度图像扩展到三维
        labels= np.expand_dims(labels,axis=2).repeat(3,axis=2).astype(np.uint8)
        # for st in stats[1:]:
        cv2.rectangle(labels, (stats[index][0], stats[index][1]), (stats[index][0]+stats[index][2], stats[index][1]+stats[index][3]), (0, 255, 0), 3)
        #cv2.imshow('labels', labels)
        #cv2.waitKey(0)
        cv2.imwrite(files_path+"/labels/"+str(i)+".png",labels)
相关推荐
好家伙VCC8 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
前端玖耀里9 小时前
如何使用python的boto库和SES发送电子邮件?
python
serve the people9 小时前
python环境搭建 (十二) pydantic和pydantic-settings类型验证与解析
java·网络·python
小天源9 小时前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
喵手9 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手10 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
2601_9491465310 小时前
Python语音通知接口接入教程:开发者快速集成AI语音API的脚本实现
人工智能·python·语音识别
寻梦csdn10 小时前
pycharm+miniconda兼容问题
ide·python·pycharm·conda
Java面试题总结11 小时前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
不懒不懒11 小时前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr