iproc.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.crop_nocopy(src, w1, h1, w2, h2)
  19. local dest
  20. if src:dim() == 3 then
  21. dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}]
  22. else -- dim == 2
  23. dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}]
  24. end
  25. return dest
  26. end
  27. function iproc.byte2float(src)
  28. local conversion = false
  29. local dest = src
  30. if src:type() == "torch.ByteTensor" then
  31. conversion = true
  32. dest = src:float():div(255.0)
  33. end
  34. return dest, conversion
  35. end
  36. function iproc.float2byte(src)
  37. local conversion = false
  38. local dest = src
  39. if src:type() == "torch.FloatTensor" then
  40. conversion = true
  41. dest = (src * 255.0):byte()
  42. end
  43. return dest, conversion
  44. end
  45. function iproc.scale(src, width, height, filter)
  46. local t = "float"
  47. if src:type() == "torch.ByteTensor" then
  48. t = "byte"
  49. end
  50. filter = filter or "Box"
  51. local im = gm.Image(src, "RGB", "DHW")
  52. im:size(math.ceil(width), math.ceil(height), filter)
  53. return im:toTensor(t, "RGB", "DHW")
  54. end
  55. function iproc.padding(img, w1, w2, h1, h2)
  56. local dst_height = img:size(2) + h1 + h2
  57. local dst_width = img:size(3) + w1 + w2
  58. local flow = torch.Tensor(2, dst_height, dst_width)
  59. flow[1] = torch.ger(torch.linspace(0, dst_height -1, dst_height), torch.ones(dst_width))
  60. flow[2] = torch.ger(torch.ones(dst_height), torch.linspace(0, dst_width - 1, dst_width))
  61. flow[1]:add(-h1)
  62. flow[2]:add(-w1)
  63. return image.warp(img, flow, "simple", false, "clamp")
  64. end
  65. return iproc