我想根据图像的右边框裁剪图像.我有大约10000张手部X射线图像需要预处理,以及到目前为止我所做的工作:
- 在图像上应用高斯模糊和阈值(二进制+Otsu).
- 应用inflating 以获取单个对象(在本例中为手).
- 用于沿手周围的边缘绘制轮廓.
- 使用
cv2.boundingRect()
查找右帧,然后使用cv2.minAreaRect()
和cv2.boxPoints
获得边界框的右点. - 使用
cv2.warpPerspective
根据高度和宽度调整图像.
下面的代码描述了上述内容:
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Load image, create mask, grayscale, Gaussian blur, Otsu's threshold
img_path = "sample_image.png"
image = cv2.imread(image_path)
original = image.copy()
blank = np.zeros(image.shape[:2], dtype = np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (33,33), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Merge text into a single contour
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
dilate = cv2.dilate(thresh, kernel, iterations = 3)
# Find contours
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key = lambda x: cv2.boundingRect(x)[0])
for c in cnts:
# Filter using contour area and aspect ratio (x1 = width, y1 = height)
x, y, x1, y1 = cv2.boundingRect(c)
if (x1 > 500) and (y1 > 700):
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
width = int(rect[1][0])
height = int(rect[1][1])
src_pts = box.astype("float32")
dst_pts = np.array([[0, height-1], [0, 0],
[width-1, 0], [width-1, height-1]], dtype="float32")
M = cv2.getPerspectiveTransform(src_pts, dst_pts)
warped = cv2.warpPerspective(image, M, (width, height))
plt.imshow(warped)
如果你看some of the images in the folder,这些就是输入.当我通过上面的代码运行这些图像时,I get an output like this.其中一些修剪得很好(拉直),但是,其中一些是90度旋转修剪的.是否有代码来解决"旋转90度输出"问题?
以下是一些图片:
图像输入:Four X-ray examples
图像输出:Returns images that are 90 degrees rotated
需要图像输出:Straightened image(仅使用Photoshop将其拉直.不想对Straightened image00张图像执行此操作…)
更新:
我根据下面提到的建议编辑了代码.运行一些样本后,它现在返回向右倾斜90度的图像.
我怀疑这是因为图像的质量.也许这与OpenCV的minAreaRect()
有关?还是boxPoints
?
FINAL 更新:
根据@Prashant Maurya的说法,代码被更新,增加了一个功能来检测手的位置是左还是右.然后将src\u pts映射到右侧dst\u pts.完整代码如下所示.