如何从图像中提取所有区域?
How can I extract all regions from an image?
我有一张如下图。图片尺寸固定:640x480
.
我想用这样的矩形来绑定所有非零区域:
我需要知道每个矩形的右上角和左下角的点。
想过循环之类的方法。但是所有这些都将花费太长时间 运行。 python 中最有效的方法是什么?
PS: 我是图像处理的初学者。这可能是一个显而易见的问题,我不知道。所以给我一个示例代码会有很大帮助。谢谢
查找图像中的所有子组件称为 connected component analysis. In OpenCV you can do it with findCountour()
function of its contour analysis 库。
这是一个示例代码:
import cv2
import numpy as np
from scipy import signal
#=========================================================================
# Locate all components
#=========================================================================
def locateComponents(img):
"""Extracts all components from an image"""
out = img.copy()
res = cv2.findContours(np.uint8(out.copy()),\
cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = res[1]
ret = []
row, col = out.shape
minSiz = 8
for cnt in contours:
# get bounding box
y, x, n, m = cv2.boundingRect(cnt)
# check area
if m < minSiz or n < minSiz:
continue
#end if
ret.append(np.int32([x, x+m, y, y+n]))
out = cv2.rectangle(out, (y,x), (y+n,x+m), (255,255,255), 2)
#end for
return ret, out
# end function
#=========================================================================
# TESTING
#=========================================================================
img = cv2.imread('input.jpg', 0)
regions, out = locateComponents(img)
cv2.imwrite('output.jpg', out)
print regions
cv2.imshow('Given image', img)
cv2.imshow('Located regions', out)
cv2.waitKey(0)
输出图像:
我有一张如下图。图片尺寸固定:640x480
.
我想用这样的矩形来绑定所有非零区域:
我需要知道每个矩形的右上角和左下角的点。
想过循环之类的方法。但是所有这些都将花费太长时间 运行。 python 中最有效的方法是什么?
PS: 我是图像处理的初学者。这可能是一个显而易见的问题,我不知道。所以给我一个示例代码会有很大帮助。谢谢
查找图像中的所有子组件称为 connected component analysis. In OpenCV you can do it with findCountour()
function of its contour analysis 库。
这是一个示例代码:
import cv2
import numpy as np
from scipy import signal
#=========================================================================
# Locate all components
#=========================================================================
def locateComponents(img):
"""Extracts all components from an image"""
out = img.copy()
res = cv2.findContours(np.uint8(out.copy()),\
cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = res[1]
ret = []
row, col = out.shape
minSiz = 8
for cnt in contours:
# get bounding box
y, x, n, m = cv2.boundingRect(cnt)
# check area
if m < minSiz or n < minSiz:
continue
#end if
ret.append(np.int32([x, x+m, y, y+n]))
out = cv2.rectangle(out, (y,x), (y+n,x+m), (255,255,255), 2)
#end for
return ret, out
# end function
#=========================================================================
# TESTING
#=========================================================================
img = cv2.imread('input.jpg', 0)
regions, out = locateComponents(img)
cv2.imwrite('output.jpg', out)
print regions
cv2.imshow('Given image', img)
cv2.imshow('Located regions', out)
cv2.waitKey(0)
输出图像: