用python求正方形面积_使用Python/OpenCV从图像中提取固定数量的正方形

我有几个扫描图像,我想用Python/Opencv计算。这些图像(见下面的示例)包含n行彩色正方形。每一个方块的大小都一样。目标是裁剪每个方块并从中提取数据。在

3eY0k.jpg

我发现了there一种能从图像中提取正方形的代码。在

以下是我使用过的代码:import numpy as np

import cv2

from matplotlib import pyplot as plt

def angle_cos(p0, p1, p2):

import numpy as np

d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')

return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )

def find_squares(img):

import cv2 as cv

import numpy as np

img = cv.GaussianBlur(img, (5, 5), 0)

squares = []

for gray in cv.split(img):

for thrs in range(0, 255, 26):

if thrs == 0:

bin = cv.Canny(gray, 0, 50, apertureSize=5)

bin = cv.dilate(bin, None)

else:

_retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)

contours, _hierarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

for cnt in contours:

cnt_len = cv.arcLength(cnt, True)

cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)

if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):

cnt = cnt.reshape(-1, 2)

max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])

if max_cos < 0.1:

squares.append(cnt)

print(len(squares))

return squares

img = cv2.imread("test_squares.jpg",1)

plt.axis("off")

plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

plt.show()

squares = find_squares(img)

cv2.drawContours( img, squares, -1, (0, 255, 0), 1 )

plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

plt.show()

但是,它会找到两个很多的正方形(100而不是15!!)。从图像来看,Opencv似乎为每个正方形找到了很多轮廓。在

我很确定它是可以优化的,因为正方形大小差不多,而且彼此相距很远。作为Opencv的一个初学者,我还没有找到一种方法在函数“find squares”中给出更多的标准,以便在例程结束时只得到15个正方形。也许轮廓面积可以最大化?在

我还发现了there一个更详细的代码(与前一个非常接近),但它似乎是在旧版本的Opencv中开发的。我还没有设法使它工作(因此修改它)。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以使用PythonOpenCV库来实现这个功能。以下是一个简单的实现步骤: 1. 导入OpenCV库 ```python import cv2 import os ``` 2. 循环读取同文件夹下的每个png图片文件 ```python for filename in os.listdir(): if filename.endswith('.png'): # 读取图片 image = cv2.imread(filename) ``` 3. 获取图片的宽和高,并确定最大边长 ```python height, width, channels = image.shape max_size = max(width, height) ``` 4. 创建一个新的正方形图片,并将原图片粘贴在正方形图片央 ```python # 创建一个新的正方形图片 square_image = np.zeros((max_size, max_size, channels), dtype=np.uint8) square_image.fill(255) # 粘贴原图片在正方形图片央 x = (max_size - width) // 2 y = (max_size - height) // 2 square_image[y:y+height, x:x+width] = image ``` 5. 保存处理后的图片 ```python # 保存图片 cv2.imwrite('square_' + filename, square_image) ``` 将以上代码整合成一个完整的程序,完整代码如下: ```python import cv2 import os import numpy as np for filename in os.listdir(): if filename.endswith('.png'): # 读取图片 image = cv2.imread(filename) # 获取图片的宽和高,并确定最大边长 height, width, channels = image.shape max_size = max(width, height) # 创建一个新的正方形图片 square_image = np.zeros((max_size, max_size, channels), dtype=np.uint8) square_image.fill(255) # 粘贴原图片在正方形图片央 x = (max_size - width) // 2 y = (max_size - height) // 2 square_image[y:y+height, x:x+width] = image # 保存图片 cv2.imwrite('square_' + filename, square_image) ``` 希望这能帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值