以下是使用Python OpenCV提取和旋转图像中每个blob的方法:
- 读取输入图像
- 转换为灰度图像
- 二值化处理
- 应用形态学开闭运算以清除小斑点
- 获取所有外部轮廓
- 遍历每个轮廓并执行以下操作:
- 在输入图像的副本上绘制轮廓
- 获取轮廓的旋转矩形,并提取其中心、尺寸和旋转角度
- 获取旋转矩形的四个角
- 在另一个输入图像的副本上绘制旋转矩形
- 校正图像反转的旋转角度
- 生成填充旋转矩形的蒙版图像
- 将蒙版图像应用于形态学清除后的图像,以删除附近的其他白色区域
- 使用中心和校正后的旋转角度获取仿射变换矩阵
- 使用warpAffine对未旋转的图像进行旋转
- 获取未旋转图像中一个blob的轮廓
- 获取轮廓的边界框
- 裁剪蒙版图像(或交替裁剪输入图像)
- 保存裁剪后的图像
- 退出循环
- 保存轮廓和旋转矩形图像
输入:
import cv2
import numpy as np
image = cv2.imread("bw2.jpg")
hh, ww = image.shape[:2]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
kernel = np.ones((7,7), np.uint8)
clean = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = np.ones((13,13), np.uint8)
clean = cv2.morphologyEx(clean, cv2.MORPH_CLOSE, kernel)
contours = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
contour_img = image.copy()
rotrect_img = image.copy()
i = 1
for c in contours:
cv2.drawContours(contour_img,[c],0,(0,0,255),2)
rotrect = cv2.minAreaRect(c)
(center), (width,height), angle = rotrect
box = cv2.boxPoints(rotrect)
boxpts = np.int0(box)
cv2.drawContours(rotrect_img,[boxpts],0,(0,255,0),2)
if angle < -45:
angle = -(90 + angle)
else:
if width > height:
angle = -(90 + angle)
else:
angle = -angle
neg_angle = -angle
mask = np.zeros_like(clean)
cv2.drawContours(mask,[boxpts],0,255,-1)
blob_img = cv2.bitwise_and(clean, mask)
M = cv2.getRotationMatrix2D(center, neg_angle, scale=1.0)
deskewed = cv2.warpAffine(blob_img, M, (ww, hh), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
deskewed = cv2.threshold(deskewed, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
cntrs = cv2.findContours(deskewed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
cntr = cntrs[0]
x,y,w,h = cv2.boundingRect(cntr)
crop = deskewed[y:y+h, x:x+w]
cv2.imwrite("bw2_deskewed_{0}.png".format(i),crop)
print("")
i = i + 1
cv2.imwrite("bw2_contours.png",contour_img)
cv2.imwrite("bw2_rotrects.png",rotrect_img)
cv2.imshow("thresh", thresh)
cv2.imshow("clean", clean)
cv2.imshow("contours", contour_img)
cv2.imshow("rectangles", rotrect_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
轮廓图像:
旋转矩形图像:
前三个未旋转的图像:
仿射变换旋转角度:
13.916877746582031
-42.87890625
18.8118896484375
-44.333797454833984
-38.65980911254883
-37.25965881347656
8.806793212890625
14.931419372558594
-37.405357360839844
-34.99202346801758
35.537681579589844
-35.350345611572266
-42.3245735168457
50.12316131591797
-42.969085693359375
52.750038146972656
45.0