【发布时间】:2021-09-06 11:49:37
【问题描述】:
- 我正在尝试仅保留 17 号批次中以橙色/绿色线为界的图像部分。
-
如您所见,形状相当不标准,而且我是图像处理的新手,所以到目前为止我的方法是蛮力且容易出错的。
-
我需要对其执行此操作的每张图像在我要裁剪的形状的中心都有一个黑点(
rgbof (77,77,77)),该形状一直是我的锚点。
import PIL
import pandas as pd
image = PIL.Image.open(file)
rgb_im = image.convert('RGB')
color = (77,77,77)
colorindex = pd.DataFrame(data = None,columns = ['X','Y'])
for x in range(image.size[0]):
for y in range(image.size[1]):
r, g, b = rgb_im.getpixel((x, y))
if (r,g,b) == color:
append = [x,y]
append = pd.Series(append,index = colorindex.columns)
colorindex = colorindex.append(append,ignore_index = True)
center = [colorindex.mode()['X'][0],colorindex.mode()['Y'][0]]
line = pd.read_excel('C:/Users/lines RGb.xlsx') ##Prerecorded RGB Values
def findparcelline(CenterX,CenterY,direction):
if direction == 'left':
for x in range(CenterX):
r,g,b = rgb_im.getpixel((CenterX-x,CenterY))
for i in range(len(line)):
if (r,g,b) == (line.loc[i][0],line.loc[i][1],line.loc[i][2]):
pixelsave = CenterX-x
return pixelsave
elif direction == 'right':
for x in range(CenterX):
r,g,b = rgb_im.getpixel((CenterX+x,CenterY))
for i in range(len(line)):
if (r,g,b) == (line.loc[i][0],line.loc[i][1],line.loc[i][2]):
pixelsave = CenterX+x
return pixelsave
elif direction == 'down':
for y in range(CenterY):
r,g,b = rgb_im.getpixel((CenterX,CenterY + y))
for i in range(len(line)):
if (r,g,b) == (line.loc[i][0],line.loc[i][1],line.loc[i][2]):
pixelsave = CenterY + y
return pixelsave
elif direction == 'up':
for y in range(CenterY):
r,g,b = rgb_im.getpixel((CenterX,CenterY - y))
for i in range(len(line)):
if (r,g,b) == (line.loc[i][0],line.loc[i][1],line.loc[i][2]):
pixelsave = CenterY - y
return pixelsave
directions = ['left','down','right','up']
coords =[]
for direction in directions:
coords.append(findparcelline(center[0],center[1],direction))
im1 = image.crop(coords)
- 我的代码仅适用于正面朝上的矩形形状(其中很多是这样的),但是当涉及到示例中的内容时它会失败。
- 我考虑过使用写到这里的代码,然后从通过 9x9 像素数组提供的像素位置“走线”,并且只选择那些:
- 之前未选择
- 匹配预先记录的颜色值
- 最接近锚像素位置
-
但在示例中,我感兴趣的行中有更多
rgb颜色值,甚至还有一些孔。 -
有没有办法获取包围中心黑点的线的坐标,然后在记录所有坐标后裁剪图像?
提前致谢。
【问题讨论】:
-
如果您知道中心(黑点)并知道您想要的矩形区域和角度,您可以计算旋转矩形的角,以便您可以定义蒙版。然后遮盖旋转矩形外的背景和/或裁剪到最小边界 XY 方向的边界框。
标签: python opencv image-processing python-imaging-library crop