iproc.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. local gm = require 'graphicsmagick'
  2. local image = require 'image'
  3. local iproc = {}
  4. function iproc.crop_mod4(src)
  5. local w = src:size(3) % 4
  6. local h = src:size(2) % 4
  7. return image.crop(src, 0, 0, src:size(3) - w, src:size(2) - h)
  8. end
  9. function iproc.crop(src, w1, h1, w2, h2)
  10. local dest
  11. if src:dim() == 3 then
  12. dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}]:clone()
  13. else -- dim == 2
  14. dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}]:clone()
  15. end
  16. return dest
  17. end
  18. function iproc.byte2float(src)
  19. local conversion = false
  20. local dest = src
  21. if src:type() == "torch.ByteTensor" then
  22. conversion = true
  23. dest = src:float():div(255.0)
  24. end
  25. return dest, conversion
  26. end
  27. function iproc.float2byte(src)
  28. local conversion = false
  29. local dest = src
  30. if src:type() == "torch.FloatTensor" then
  31. conversion = true
  32. dest = (src * 255.0):byte()
  33. end
  34. return dest, conversion
  35. end
  36. function iproc.scale(src, width, height, filter)
  37. local t = "float"
  38. if src:type() == "torch.ByteTensor" then
  39. t = "byte"
  40. end
  41. filter = filter or "Box"
  42. local im = gm.Image(src, "RGB", "DHW")
  43. im:size(math.ceil(width), math.ceil(height), filter)
  44. return im:toTensor(t, "RGB", "DHW")
  45. end
  46. function iproc.padding(img, w1, w2, h1, h2)
  47. local dst_height = img:size(2) + h1 + h2
  48. local dst_width = img:size(3) + w1 + w2
  49. local flow = torch.Tensor(2, dst_height, dst_width)
  50. flow[1] = torch.ger(torch.linspace(0, dst_height -1, dst_height), torch.ones(dst_width))
  51. flow[2] = torch.ger(torch.ones(dst_height), torch.linspace(0, dst_width - 1, dst_width))
  52. flow[1]:add(-h1)
  53. flow[2]:add(-w1)
  54. return image.warp(img, flow, "simple", false, "clamp")
  55. end
  56. return iproc