我有这样的图像
在图像的上半部分,我想要裁剪一些不相关的空间。我在这里标记了它:
前几行中的黑色像素数量大致相同。
所以我的想法是从顶部(第0行)开始循环遍历此图像的行,然后检查行+10是否具有相同数量的黑色像素。
如果是,继续,如果不是,这是断点。
然而,我无法让它发挥作用。这是我的代码
for i in range(img.shape[0]):
low = sum(np.bincount(img[i,:])[0:5]) # number of black pixels
high = sum(np.bincount(img[i+10,:])[0:5]) #number of black pixels in row i+10
#print(i)
if(low-low*0.01 < high):
print(i)
break
然后裁剪图片:
imcrop = img[int(0+i):,:]
with np.bincount
我总结了五个最黑暗像素的数量(0 =黑色,255 =白色)
然后循环,直到找到断点。
通过试验阈值水平,我发现输出0或数字过高。
最好的办法是什么?
答案 0 :(得分:1)
相当缓慢但有效。首先从左向右移动以找到黑色像素和其他像素之间的边界。之后从右向左移动以找到黑色和其他像素之间的边界。最后,我们得到两个边界列表left_data和right_data。 从第一行检查左边界到右边界之间的距离并移动直到距离相同然后停止。最后,我们得到了所需图像的四个角落。
import cv2
image = cv2.imread('sample.png') #Test Image
image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
height = image.shape[0]
width = image.shape[1]
Black = 0
left = 0
right = 0
data_left = [] #left boundary
data_right = [] #right boundary
for i in range(height):
for j in range(width-1):
first = image[i][j]
second = image[i][j+1]
if(first==Black and second!=Black):
left=j
data_left.append(left)
for i in range(height):
j = width-1
found = 0
while(found==0 and j>=0):
first = image[i][j]
second = image[i][j-1]
if(first==Black and second != Black):
right = j
found = 1
j = j-1
data_right.append(right)
left_start = [0,data_left[0]]
right_start = [0,data_right[0]]
left_end = 0
right_end = 0
i = 0
found = 0
while(i<len(data_left) and found == 0):
if((data_left[i]==left_start[1] and data_right[i]==right_start[1])==False):
found = 1
left_end = [i,data_left[i]]
right_end = [i,data_right[i]]
i = i+1
width = data_right[0]-data_left[0]
height = left_end[0]
pos_y = 0
pos_x = data_left[0]
crop_image = image[pos_y:pos_y+height, pos_x:pos_x+width]
cv2.imwrite('result.jpg',crop_image) # result image
原始图片
结果图片
答案 1 :(得分:0)
在openCV中裁剪图像
crop_img = img[200:400, 100:300]
其中100和300是图像裁剪的宽度和高度,200和400是图像裁剪的左上角坐标。