ain*_*ka7 2 python opencv image-processing
有谁能告诉我如何将图像的二分为上下部分?所以我可以重叠它们.例如,我有一个图像,我应该划分它来计算每个部分的像素数.我是OpenCV的新手,并不完全了解图像的几何形状.
为了简化@ avereux的答案:
在Python中,您可以使用拼接将图像分解为子图像.这个语法是:
sub_image = full_image[y_start: y_end, x_start:x_end]
Run Code Online (Sandbox Code Playgroud)
请注意,对于图像,原点是图像的左上角.因此,图像第一行(即最顶行)上的像素将具有坐标x_coordinate = x,y_coordinate = 0
要获得图像的形状,请使用image.shape.这回来了(no_of_rows, no_of_cols)
您可以使用它们以您想要的方式分解图像.
您可以水平向下裁剪图像的顶部和底部.
打开图像.
import cv2
import numpy as np
image = cv2.imread('images/blobs1.png')
cv2.imshow("Original Image", image)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
使用image.shape让我们捕捉到的高度和宽度的变量.
height, width = image.shape[:2]
print image.shape
Run Code Online (Sandbox Code Playgroud)
现在我们可以开始裁剪了.
# Let's get the starting pixel coordiantes (top left of cropped top)
start_row, start_col = int(0), int(0)
# Let's get the ending pixel coordinates (bottom right of cropped top)
end_row, end_col = int(height * .5), int(width)
cropped_top = image[start_row:end_row , start_col:end_col]
print start_row, end_row
print start_col, end_col
cv2.imshow("Cropped Top", cropped_top)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Let's get the starting pixel coordiantes (top left of cropped bottom)
start_row, start_col = int(height * .5), int(0)
# Let's get the ending pixel coordinates (bottom right of cropped bottom)
end_row, end_col = int(height), int(width)
cropped_bot = image[start_row:end_row , start_col:end_col]
print start_row, end_row
print start_col, end_col
cv2.imshow("Cropped Bot", cropped_bot)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
最后,我们可以使用image.size每个部分中的像素数.
cropped_top.size
cropped_bot.size
Run Code Online (Sandbox Code Playgroud)
你可以用轮廓做同样的事情,但它会涉及边界框.
这是更灵活的方法,您可以根据需要将图像切成两半或分成 4 等份或 6 份。
此代码将首先将图像水平裁剪为 2 块,然后对于这 2 块中的每一块,它将裁剪另外 3 个图像,总共留下 6 个裁剪图像更改 CROP_W_SIZE 和 CROP_H_SIZE 值以调整裁剪设置。您将需要一个 CROP 文件夹,此代码将在其中保存图像。
import cv2,time
img = cv2.imread('image.png')
img2 = img
height, width, channels = img.shape
# Number of pieces Horizontally
CROP_W_SIZE = 3
# Number of pieces Vertically to each Horizontal
CROP_H_SIZE = 2
for ih in range(CROP_H_SIZE ):
for iw in range(CROP_W_SIZE ):
x = width/CROP_W_SIZE * iw
y = height/CROP_H_SIZE * ih
h = (height / CROP_H_SIZE)
w = (width / CROP_W_SIZE )
print(x,y,h,w)
img = img[y:y+h, x:x+w]
NAME = str(time.time())
cv2.imwrite("CROP/" + str(time.time()) + ".png",img)
img = img2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10117 次 |
| 最近记录: |