如何从以下没有文本的图像中提取9张图像?

时间:2018-08-15 06:37:53

标签: image image-processing

2 个答案:

答案 0 :(得分:2)

您可以使用 ImageMagick 进行此操作,该软件安装在大多数Linux发行版中,并且可用于macOS和Windows。

这可以在终端的命令行中完成。因此,首先我们要确定图像区域并拒绝文本。最简单的方法是将所有饱和色设为白色,将所有灰色/不饱和色设为黑色:

convert dna.png -fx "saturation<0.5? 0 : 1" z.jpg

enter image description here

现在,我们可以执行“斑点分析” “连接组件分析” 来找到白色的“斑点” ,如下所示:

convert dna.png -fx "saturation<0.5? 0 : 1"       \
    -define connected-components:verbose=true     \
    -connected-components 8 -auto-level output.png

示例输出

Objects (id: bounding-box centroid area mean-color):
  0: 314x112+0+0 155.2,56.1 28249 srgba(0,0,0,2.31991)
  3: 100x16+214+23 262.9,30.4 1576 srgba(255,255,255,42.5831)
  2: 100x16+108+23 157.1,30.1 1511 srgba(255,255,255,44.3719)
  9: 100x8+2+88 50.4,91.4 777 srgba(255,255,255,85.3436)       <--- THIS ONE
  6: 100x7+2+55 50.7,57.9 687 srgba(255,255,255,96.393)
  1: 100x6+2+23 50.5,25.4 587 srgba(255,255,255,112.644)
  10: 100x6+108+96 156.9,98.0 507 srgba(255,255,255,130.26)
  7: 100x5+108+65 155.6,66.9 477 srgba(255,255,255,138.39)
  8: 100x5+214+65 263.3,66.5 399 srgba(255,255,255,165.248)
  11: 100x5+214+96 263.2,97.5 396 srgba(255,255,255,166.492)
  5: 1x1+110+33 110.0,33.0 1 srgba(0,0,0,65535)
  4: 1x1+200+27 200.0,27.0 1 srgba(0,0,0,65535)

有一个标题/标题行,然后在图像中找到的每个斑点都有一行。让我们看一下这行:

 9: 100x8+2+88 50.4,91.4 777 srgba(255,255,255,85.3436) 

这意味着在距左上角偏移(2,88)处有一个大小为100x8像素的斑点。让我们用半透明的红色填充它:

 convert dna.png -stroke red -fill "rgba(255,0,0,0.5)" -draw "rectangle 2,88 102,96" p.png

enter image description here

然后将其裁剪为新图像:

convert dna.png -crop 100x8+2+88 +repage result.png

enter image description here

一个小的awk脚本会为您获得其他斑点。

答案 1 :(得分:1)

如果您不喜欢命令行方法,我已经在 Python 中重铸了我的 ImageMagick 答案。我是 Python 的初学者,因此我的代码可能效率低下,操作不当,但可以使用。该技术与其他答案完全相同:

  • 转换为HSV色彩空间,并找到高度饱和(彩色)的像素,
  • skimage 运行label()进行“连接的组件” 标记,
  • 提取blob并另存为文件。

#!/usr/local/bin/python3

import numpy as np
from PIL import Image
from skimage import color
from skimage.measure import label, regionprops

# Load image and convert to RGB discarding any alpha
im=np.array(Image.open('dna.png').convert('RGB'))

# Add 1px black border all around so shapes don't touch edges
blackcanvas=np.zeros((im.shape[0]+2,im.shape[1]+2,3))
blackcanvas[1:-1,1:-1]=im
im=blackcanvas

# Convert to HSV colourspace, discard H, V and find saturated (i.e. brightly coloured) pixels
HSV=color.rgb2hsv(im)
S=HSV[:,:,1]
bw=(S>0.5)*255

# Image is now white blobs on black background, so label() it
label_image=label(bw)

# Iterate through blobs, saving each to disk
i=0
for region in regionprops(label_image):
   if region.area >= 100:
      # Extract rectangle containing blob and save
      name="blob-" + str(i) + ".png"
      minr, minc, maxr, maxc = region.bbox
      Image.fromarray(im[minr:maxr,minc:maxc,:].astype(np.uint8)).save(name)
      i = i + 1

enter image description here