gpt4 book ai didi

python - OPENCV 如何补齐缺失的矩形?

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:51 24 4
gpt4 key购买 nike

我的问题太简单了。我有一个这样的矩形。我想填补这个广场的缺失部分。我还需要缺失部分的坐标。我怎样才能做到这一点? Rectangle

我应该像处理后的第二张图片。 Second Image

最佳答案

这里是这个方法的总结:

  1. 逐行水平扫描
  2. 逐列垂直扫描
  3. 准备一份潜在积分列表
  4. 按距离对点进行分组
  5. 找到子分组点周围的边界框
  6. 计算矩形并忽略那些触及图像边界的矩形。

源代码:

首先,导入所需的库。

import numpy as np
import cv2

其次,定义一个计算两点之间距离的函数,更重要的是,它允许您决定是否要在终端中打印"too easy"

def too_easy_distance(pt1, pt2, is_print=False):
if is_print: print ("too easy!")
return ((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) ** 0.5

第三,载入图片,求宽高。

img = cv2.imread("broken_rect.png", 0)
height, width = img.shape[:2]
active_threshold = 25 # adjust this parameter based on the thickness of borders
potential_pts = []

现在,逐行水平扫描图像。

for i in range(height):
if len (np.where(img[i:i+1,:]==0)[1] ) < active_threshold:
continue
is_start = False
is_real_start = False
for j in range(width):
if img[i,j] == 0 and is_start is False:
is_start = True
continue
# Enter the valid region
if is_start and is_real_start is False:
if img[i,j] == 255:
is_real_start = True
else:
is_real_start = False

if is_real_start:
if img[i,j] == 255:
potential_pts.append((j, i))
else:
is_real_start = False

然后,逐列垂直扫描图像。

for j in range(width):
if len (np.where(img[:, j:j+1]==0)[1] ) < active_threshold:
continue
is_start = False
is_real_start = False
for i in range(height):
if img[i,j] == 0 and is_start is False:
is_start = True
continue
# Enter the valid region
if is_start and is_real_start is False:
if img[i,j] == 255:
is_real_start = True
else:
is_real_start = False

if is_real_start:
if img[i,j] == 255:
potential_pts.append((j, i))
else:
is_real_start = False

最后,对列表进行排序,并显示结果图片。

grouped_pts = []  #list of list
for pt in potential_pts:
if len(grouped_pts) == 0:
grouped_pts.append([pt]) # create a new sublist and add pt to the new sublist
# enter the grouped_pts loop
is_found_place = False
for sublist in grouped_pts:
for prev_pt in sublist:
if too_easy_distance(pt, prev_pt) < 2:
sublist.append(pt) # add to the list
is_found_place = True
break
# if nothing happend
if is_found_place is False:
grouped_pts.append([pt]) # create a new sublist and add pt to the new sublist

result_image = cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2RGB)

for sublist in grouped_pts:
x,y,w,h = cv2.boundingRect(np.array(sublist))
if x == 0 or y == 0 or x+w == width or y+h == height:
continue

rect = ((x, y), (x+w-1, y+h-1))
cv2.rectangle(result_image, rect[0], rect[1], (0,255,0), -1)
print ("Rect Found! [Top-Left]: " + str(rect[0]) + " [Bottom-Right]: " + str([rect[1]]) )

cv2.imshow("result_image", result_image)
cv2.waitKey()

结果图片: Result Image

终端输出:

Rect Found! [Top-Left]: (267, 62) [Bottom-Right]: [(313, 69)]
Rect Found! [Top-Left]: (552, 327) [Bottom-Right]: [(559, 364)]

关于python - OPENCV 如何补齐缺失的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com