自然场景实验材料处理工具(2)

事实再一次证明,要用正确的工具做正确的事情。编程语言并没有好坏之分(至少在大部分应用情景下),我在自然场景实验材料处理工具(1)中用 Go 做了一些简单的图片尺寸过滤、裁减、缩放等处理,虽然也可以很好完成任务,但第二个实验中的实验材料稍有不同,处理方式也稍有不同,重新修改调试的时间成本可能要比 Python + OpenCV 重做还要高。总之,理性对待工具,Don't get too attached to things -,-

主要用 Python + OpenCV 几何处理的方法:

1. 过滤尺寸

import cv2

def validSize(imgin, s):
  img = cv2.imread(imgin, 1)
  (h, w, d) = img.shape
  if h < s or w < s:
    return  False
  return True

2. 裁减周围 N pix

import cv2

def crop(imgin, imgout, N):
  img = cv2.imread(imgin, 1)
  (h, w, d) = img.shape
  if h <= 2 * N or w <= 2 * N:
    print "To smale to crop %s!" % imgin
    return
  cropped = img[N:h-N, N:w-N, :]

  cv2.imwrite(imgout, cropped)

3. 裁剪至比例后缩放

import cv2

def scaleTo(imgin, imgout, W, H):
  img = cv2.imread(imgin, 1)
  (h, w, d) = img.shape

  if h * 1.0 / w <= H * 1.0 / W:
    w2 = int(1.0 * h * W / H)
    img = img[:, int(1.0 * (w - w2)/2):int(1.0 * (w - w2)/2)+w2, :]
  else:
    h2 = int(1.0 * H * w / W)
    img = img[int(1.0 * (h - h2) / 2):int(1.0 * (h - h2) / 2)+h2,:,:]

  dest = cv2.resize(img, (W, H), interpolation = cv2.INTER_CUBIC)
  cv2.imwrite(imgout, dest)

参考:

  1. Geometric Transformations of Images