导入库
import cv2 as cv
import os
定义一个路径字符串,指向桌面上的一个文件夹
path = r'C:\Users\RANDALL\Desktop\ce\ceshi-20231031\saizhi\part3\file1\photo'
使用os.listdir函数列出指定路径下的所有文件和文件夹
for file in os.listdir(path):
拼接文件路径,img变量保存的是完整的文件路径
img = os.path.join(path,file)
使用cv2的imread函数读取一张图片,并将其保存到image变量中
image = cv.imread(r"C:\Users\RANDALL\Desktop\wenzi\ren.jpg")
将读取的图片从BGR颜色空间转换为灰度颜色空间
gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
对灰度图片进行阈值化处理,将像素值高于150的设为255,低于150的设为0,生成二值化图像thresh
ret,thresh = cv.threshold(gray,150,255,cv.THRESH_BINARY)
使用findContours函数查找二值化图像中的轮廓,返回轮廓信息以及轮廓的层级结构
contours,herarchy = cv.findContours(thresh,cv.RETR_LIST,cv.CHAIN_APPROX_NONE)
使用drawContours函数在原图上绘制出找到的轮廓,轮廓的颜色为红色,线条宽度为2
draw = cv.drawContours(image,contours,-1,(0,0,255),2)
使用imshow函数显示图像,并命名为'demo2',图像显示完毕后需要使用waitKey函数等待用户按键关闭窗口
cv.imshow('demo2',image)
cv.waitKey(0)
运行结果
完整代码
import cv2 as cv
import os
path = r'C:\Users\RANDALL\Desktop\ce\ceshi-20231031\saizhi\part3\file1\photo'
for file in os.listdir(path):
img = os.path.join(path,file)
image = cv.imread(r"C:\Users\RANDALL\Desktop\wenzi\ren.jpg")
gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(gray,150,255,cv.THRESH_BINARY)
contours,herarchy = cv.findContours(thresh,cv.RETR_LIST,cv.CHAIN_APPROX_NONE)
draw = cv.drawContours(image,contours,-1,(0,0,255),2)
cv.imshow('demo2',image)
cv.waitKey(0)
如果文章对你有所帮助,麻烦动动小手点点关注!!!