python - 从给定 4 个点坐标的图像中提取任意矩形块
问题描述
给定图像中四个任意点的坐标(保证形成一个矩形),我想提取它们表示的补丁并获得相同的矢量化(平面)表示。我怎样才能做到这一点?
我看到了这个问题的答案,使用它我可以找到我需要的补丁。例如,给定此图像中绿色矩形的 4 个角的图像坐标:
我能够得到补丁并得到类似的东西:
使用以下代码:
p1 = (334,128)
p2 = (438,189)
p3 = (396,261)
p4 = (292,200)
pts = np.array([p1, p2, p3, p4])
mask = np.zeros((img.shape[0], img.shape[1]))
cv2.fillConvexPoly(mask, pts, 1)
mask = mask.astype(np.bool)
out = np.zeros_like(img)
out[mask] = img[mask]
patch = img[mask]
cv2.imwrite(img_name, out)
但是,问题在于patch
,当图像以行优先顺序作为矩阵读取时,我获得的变量只是属于补丁的图像的所有像素的数组。
我想要的是该patch
变量应该包含像素,以便它们可以形成真实图像,以便我可以对其执行操作。是否有一个我应该知道的 opencv 函数可以帮助我做到这一点?
谢谢!
解决方案
这是您可以实现的方法:
代码:
# create a subimage with the outer limits of the points
subimg = out[128:261,292:438]
# calculate the angle between the 2 'lowest' points, the 'bottom' line
myradians = math.atan2(p3[0]-p4[0], p3[1]-p4[1])
# convert to degrees
mydegrees = 90-math.degrees(myradians)
# create rotationmatrix
h,w = subimg.shape[:2]
center = (h/2,w/2)
M = cv2.getRotationMatrix2D(center, mydegrees, 1)
# rotate subimage
rotatedImg = cv2.warpAffine(subimg, M, (h, w))
接下来,可以通过删除所有 100% 黑色的行/列来轻松裁剪图像中的黑色区域。
最终结果:
代码:
# converto image to grayscale
img = cv2.cvtColor(rotatedImg, cv2.COLOR_BGR2GRAY)
# sum each row and each volumn of the image
sumOfCols = np.sum(img, axis=0)
sumOfRows = np.sum(img, axis=1)
# Find the first and last row / column that has a sum value greater than zero,
# which means its not all black. Store the found values in variables
for i in range(len(sumOfCols)):
if sumOfCols[i] > 0:
x1 = i
print('First col: ' + str(i))
break
for i in range(len(sumOfCols)-1,-1,-1):
if sumOfCols[i] > 0:
x2 = i
print('Last col: ' + str(i))
break
for i in range(len(sumOfRows)):
if sumOfRows[i] > 0:
y1 = i
print('First row: ' + str(i))
break
for i in range(len(sumOfRows)-1,-1,-1):
if sumOfRows[i] > 0:
y2 = i
print('Last row: ' + str(i))
break
# create a new image based on the found values
finalImage = rotatedImg[y1:y2,x1:x2]
推荐阅读
- git - 我的同事使用 git 存储库共享了一个 zip 文件,但我在 GitHub 中看不到提取的文件。我应该使用什么命令?
- python - 在小部件 PyQt5 上设置布局后更改布局
- angular - 如何将来自后端的数据水平放置在引导水平卡中
- c# - C# 关键字“this”在当前上下文中不可用
- react-native - ReferenceError:“样式”未定义
- sql - Big Query - 使用 CTE 断言?
- amazon-web-services - 为什么我看不到 CloudWatch Logs for Lambda 函数?
- python - Youtube_dl:错误:YouTube 说:无法提取视频数据
- python - Pandas 重复测量平均值
- python - 在熊猫数据框中对具有相同字符串 ID 的列求和