我有一张如下图片。它在图像的顶部和右侧有黑色边框/区域。我希望能够找到第二张图片中显示的这些区域。请注意,这些区域应始终是直的(即矩形)。我希望能够使用'图像处理代码而不是使用photoshop' (例如matlab,c#或opencv)。
我对图像处理过程非常陌生。我试图找到所有具有(0,0,0)rgb值的pionts。但是因为噪声部分(以及图像中的任何其他位置)中存在这么多黑色值。我的结果区域也包含这些不需要的区域......
----------编辑--------------- 感谢所有评论/答案。但是,我有很多这些图像。其中一些是旋转的,这有点难以处理。我刚刚上传了一个,如下所示。
答案 0 :(得分:1)
使用Python2.7 + OpenCV3。我们的想法是只保留非零行和列。代码如下。
import cv2
import numpy as np
#Read in the image
arr = np.array(cv2.imread('image.jpg'))
#Convert to grayscale
gray = np.sum(arr, axis=2)
print gray.shape #(496, 1536)
filter_row = np.sum(gray,axis=1)!=0
# Assuming first few values are all False, find index of first True, and set all values True after that
filter_row[list(filter_row).index(True):,] = True
# Keep only non-zero rows
horiz = gray[filter_row,:]
filter_column = np.sum(gray,axis=0)!=0
# Assuming first few values are all False, find index of first False, and set all values True before that
filter_column[:list(filter_column).index(False),] = True
# Keep only non-zero columns
vert = horiz[:,filter_column]
print vert.shape #(472, 1528)
bordered = cv2.rectangle(cv2.imread('image.jpg'), (0, gray.shape[0]-vert.shape[0]), (vert.shape[1],gray.shape[0] ), (255,0,0), 2)
cv2.imwrite(bordered,'result.jpg')
答案 1 :(得分:1)
color_img = imread('0k4Kh.jpg');
img = rgb2gray(color_img);
[x, y] = size(img);
for i = 1:x
if length(find(img(i, :))) ~= 0
lastmarginalrow = i-1;
break;
end
end
for ii = y:-1:1
if length(find(img(:, ii))) ~= 0
lastmarginalcol = ii-1;
break;
end
end
figure;
fig = imshow(color_img);
h = impoly(gca, [0,x; lastmarginalcol,x; lastmarginalcol,lastmarginalrow; 0,lastmarginalrow]);
api = iptgetapi(h);
api.setColor('red');
saveas(fig, 'test.jpg');
close all;
这是MATLAB中的实现。找到零列和零行并使用它们绘制边框。
对于旋转图像(也适用于非旋转图像)
color_img = imread('N6vK9.png');
img = rgb2gray(color_img);
[x, y] = size(img);
verts = [];
% traversing through all columns
for i = 1:y
% find all non-zero pixels in each column
nonzeros = find(img(:,i));
% if all pixels are black in a column, below if condition will skip
if length(nonzeros) ~= 0
% if there is atleast one non-zero pixel, not that co-oridinate/positions in matrix by appending
verts = [i, nonzeros(1); verts];
end
end
figure;
fig = imshow(color_img);
% polygon based on first and last vertix/co-ordinate of found non-zero co-ordinates
% Assumed that it was slanted straight line, used last and first co-ordinate. If it is curvy border, anyways we have all veritices/co-ordinates of first non-zero pixel in all columns.
h = impoly(gca, [verts(1,:); verts(length(verts), :); 1,x; verts(1),x]);
api = iptgetapi(h);
api.setColor('red');
saveas(fig, 'test.jpg');
close all;