增强图片清晰度解决图像模糊问题找到图像最佳分辨率的python脚本程序
以下是一个使用Python的脚本程序,用于增强图像的清晰度和解决图像模糊问题,并找到图像的最佳分辨率。
import cv2
import numpy as np
def enhance_image(image_path):
# 读取图像
img = cv2.imread(image_path)
# 灰度化图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用Sobel算子进行边缘检测
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
edges = cv2.Canny(np.uint8(sobelx), np.uint8(sobely), threshold1=10, threshold2=100)
# 膨胀操作,增强边缘
kernel = np.ones((5,5),np.uint8)
dilation = cv2.dilate(edges,kernel,iterations = 1)
# 寻找轮廓并画出边框
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
# 显示图像
cv2.imshow("Enhanced Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def find_best_resolution(image_path):
# 读取图像
img = cv2.imread(image_path)
# 获取图像大小
height, width, channels = img.shape
# 计算所有可能的分辨率
resolutions = []
for i in range(1, 10):
r = (width//i, height//i)
if r not in resolutions:
resolutions.append(r)
# 计算每种分辨率下的清晰度
scores = []
for r in resolutions:
resized = cv2.resize(img, r)
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
score = np.var(laplacian)
scores.append(score)
# 找到最佳分辨率
best_idx = scores.index(max(scores))
best_resolution = resolutions[best_idx]
# 返回最佳分辨率
return best_resolution
# 测试
image_path = "test.jpg"
enhance_image(image_path)
best_resolution = find_best_resolution(image_path)
print("Best resolution:", best_resolution)
该脚本程序包含两个函数,一个用于增强图像的清晰度,另一个用于找到图像的最佳分辨率。使用cv2.Sobel算子进行边缘检测,并使用膨胀操作增强边缘,然后找到轮廓并画出边框,从而增强图像的清晰度。使用cv2.Laplacian算子计算每种可能的分辨率下的清晰度,并返回最佳分辨率
原文地址: http://www.cveoy.top/t/topic/cpVP 著作权归作者所有。请勿转载和采集!