python-根据空白分割图像

时间:2020-08-05 20:07:47

标签: python image opencv split

我正在尝试将this image分成相等的部分,气泡行之间的“空白”是在这些部分中,然后将所有这些子图像并排成一个长图像,以便垂直排列问题。如何使用python这样分割图像?我这样做是为了使用OpenCV对气泡表进行评分。请记住,我是python的新手(但不是编码人员),因此,如果您能解释每个代码块打算做什么,那就太好了。

1 个答案:

答案 0 :(得分:4)

这是在Python / OpenCV中执行此操作的一种方法。

  • 阅读输入内容
  • 将边框颜色的颜色阈值用作遮罩
  • 使用遮罩使边框变白
  • 将面罩稍微扩张一下,以包括黑色边框线
  • 将结果转换为灰度
  • 大津门槛
  • 应用形态打开以将文本连接到列状区域并反转
  • 在列表中获取外部轮廓及其边界框
  • 计算所有框的最大宽度
  • 环绕每个框,进行填充并与前一个框堆叠
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np

# read input image
img = cv2.imread('abcd_test.png')

# define border color
lower = (0, 80, 110)
upper = (0, 120, 150)

# threshold on border color
mask = cv2.inRange(img, lower, upper)

# dilate threshold
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)

# recolor border to white
img[mask==255] = (255,255,255)

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# otsu threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU )[1] 

# apply morphology open
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17,17))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
morph = 255 - morph

# find contours and bounding boxes
bboxes = []
bboxes_img = img.copy()
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    cv2.rectangle(bboxes_img, (x, y), (x+w, y+h), (0, 0, 255), 1)
    bboxes.append((x,y,w,h))

# get largest width of bboxes
maxwidth = max(bboxes)[2]

# sort bboxes on x coordinate
def takeFirst(elem):
    return elem[0]

bboxes.sort(key=takeFirst)

# stack cropped boxes with 10 pixels padding all around
result = np.full((1,maxwidth+20,3), (255,255,255), dtype=np.uint8)
for bbox in bboxes:
    (x,y,w,h) = bbox
    crop = img[y-10:y+h+10, x-10:x+maxwidth+10]
    result = np.vstack((result, crop))

# save result
cv2.imwrite("abcd_test_mask.jpg", mask)
cv2.imwrite("abcd_test_white_border.jpg", img)
cv2.imwrite("abcd_test_thresh.jpg", thresh)
cv2.imwrite("abcd_test_morph.jpg", morph)
cv2.imwrite("abcd_test_bboxes.jpg", bboxes_img)
cv2.imwrite("abcd_test_column_stack.png", result)

# show images
cv2.imshow("mask", mask)
cv2.imshow("img", img)
cv2.imshow("thresh", thresh)
cv2.imshow("morph", morph)
cv2.imshow("bboxes_img", bboxes_img)
cv2.imshow("result", result)
cv2.waitKey(0)

边界蒙版图像:

enter image description here

带有边框的图像更改为白色:

enter image description here

阈值和形态图像:

enter image description here

边界框图像:

enter image description here

裁剪和堆叠的列图像:

enter image description here