对焦取框算法

 1 import cv2
 2 import numpy as np
 3 
 4 # 读取原始图像
 5 original_image = cv2.imread('train16.png')
 6 
 7 # 高斯模糊处理
 8 blurred_image = cv2.GaussianBlur(original_image, (5, 5), 0)
 9 
10 # 计算新图像
11 new_image = cv2.subtract(original_image, blurred_image)
12 
13 # 转换新图像为灰度图
14 gray_new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY)
15 
16 # 计算图像的形状
17 M, N = gray_new_image.shape
18 
19 # 计算新图像的灰度加权质心
20 sum_intensity = np.sum(gray_new_image)
21 
22 # 计算加权和
23 sum_x = 0.0
24 sum_y = 0.0
25 
26 for y in range(M):
27     for x in range(N):   
28         sum_x += x * gray_new_image[y, x]
29         sum_y += y * gray_new_image[y, x]
30 
31 x_c = int(sum_x / sum_intensity)
32 y_c = int(sum_y / sum_intensity)
33 
34 # 设置框的大小参数
35 box_scale = 0.45  # 框相对于图像大小的比例
36 
37 # 计算框的大小
38 box_width = int(N * box_scale)
39 box_height = int(M * box_scale)
40 
41 # 计算框的左上角和右下角坐标
42 x1 = max(0, x_c - box_width // 2)
43 y1 = max(0, y_c - box_height // 2)
44 x2 = min(N, x_c + box_width // 2)
45 y2 = min(M, y_c + box_height // 2)
46 
47 # 在原始图像上同时标注质心和框
48 image_with_center_and_box = original_image.copy()
49 image_with_center_and_box = cv2.circle(image_with_center_and_box, (x_c, y_c), 5, (255, 0, 0), -1)# 在质心位置画一个蓝色实心圆
50 image_with_center_and_box = cv2.rectangle(image_with_center_and_box, (x1, y1), (x2, y2), (0, 255, 0), 2)  # 在框的位置画一个绿色矩形

对输入的图像进行高斯模糊处理,计算出新图像后,找到图像的灰度加权质心,并在该质心周围绘制一个矩形框,用于标记图像中的重要区域。《

Analysis and comparison of automatic image focusing algorithms in digital
image processing

blurred_image = cv2.GaussianBlur(original_image, (5, 5), 0): 对原始图像进行高斯模糊处理,使用5x5的内核大小。

new_image = cv2.subtract(original_image, blurred_image): 计算原始图像与模糊图像的差异,得到新的图像。

gray_new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY): 将新图像转换为灰度图像,方便后续处理。

获取图像的形状信息:

M, N = gray_new_image.shape: 获取灰度图像的高度和宽度。

计算新图像的灰度加权质心:

遍历图像的每个像素,计算加权和以及加权质心的坐标。

 

计算框的大小和位置:

box_scale = 0.45: 设置框相对于图像大小的比例。
根据加权质心的坐标和比例计算框的大小。
计算框的左上角和右下角坐标,确保框在图像范围内。

posted @ 2024-03-25 13:30  cupwym  阅读(2)  评论(0编辑  收藏  举报