图像处理Python判断一张图像是否亮度过低,图片模糊判定
亮度判断
比如:
直方图:
代码:
这段代码是一个用于判断图像亮度是否过暗的函数is_dark,并对输入的图像进行可视化直方图展示。
首先,通过import语句导入了cv2和matplotlib.pyplot模块,用于图像处理和可视化。
is_dark函数的作用是判断输入图像的平均亮度是否低于设定的阈值。函数接受两个参数:image_path表示图像文件的路径,threshold表示亮度阈值,默认为100。函数内部的步骤如下:
使用cv2.imread函数读取图像文件,将图像存储在变量img中。
使用cv2.cvtColor函数将图像转换为灰度图像,存储在变量gray中。
使用cv2.mean函数计算灰度图像的平均亮度,存储在变量average_brightness中。
判断average_brightness是否低于设定的阈值threshold,如果是,则返回True表示图像光线过暗;否则返回False表示图像光线正常。
接下来是测试代码部分:
定义了一个图像文件的路径image_path,这里是一个示例路径,请根据实际情况修改。
调用is_dark函数判断图像光线是否过暗,如果返回True,说明图像光线过暗,输出"图片光线过暗";如果返回False,说明图像光线正常,输出"图片光线正常"。
最后,使用cv2.imread函数再次读取图像文件,将图像存储在变量img中。然后使用plt.hist函数绘制灰度图像的直方图,并通过plt.xlabel和plt.ylabel设置横轴和纵轴的标签。最后使用plt.show显示直方图。这样可以直观地查看图像的亮度分布情况。
import cv2
import matplotlib.pyplot as plt
def is_dark(image_path, threshold=100):
# 读取图像
img = cv2.imread(image_path)
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算灰度图像的平均亮度
average_brightness = cv2.mean(gray)[0]
# 判断亮度是否低于阈值
if average_brightness < threshold:
return True
else:
return False
# 测试代码
image_path = r'E:\facedata\img_data_new\10001normal_face\10001normal_face_0.5893__041430.jpg'
if is_dark(image_path):
print("图片光线过暗")
else:
print("图片光线正常")
# 可视化直方图
img = cv2.imread(image_path)
plt.hist(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).ravel(), bins=256, color='gray')
plt.xlabel('Pixel Value')
plt.ylabel('Frequency')
plt.show()
模糊判断
import os
import cv2
from tqdm import tqdm
def is_blurry(image_path):
image = cv2.imread(image_path)
if image is None:
raise Exception("无法读取图片")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur_score = cv2.Laplacian(gray, cv2.CV_64F).var()
return str(round(blur_score * 100)).rjust(10, "0")
def listPathAllfiles(dirname):
result = []
for maindir, subdir, file_name_list in os.walk(dirname):
for filename in file_name_list:
apath = os.path.join(maindir, filename)
result.append(apath)
return result
windowspath = r"E:\facedata\img_data_new"
files = listPathAllfiles(windowspath)
for filename in tqdm(files):
try:
num = is_blurry(filename)
except:
num = str(round(0 * 100)).rjust(10, "0")
new_file_name = num "____" os.path.basename(filename)
new_file_name = os.path.join(os.path.dirname(filename), new_file_name)
os.rename(filename, new_file_name)
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgcfiee
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01