Various compilation scripts & patches for Linux programs.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
14 KiB

7 years ago
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. # 3rd attempt
  4. # 15th Feb 2012, 09:38AM
  5. # http://eayd.in
  6. # http://github.com/eaydin/cr2fits
  7. ### This script is redistributable in anyway.
  8. ### But it includes netpbmfile.py which is NOT written by M. Emre Aydin.
  9. ### It has its own copyright and it has been stated in the source code.
  10. ### BUT, there's nothing to worry about usage, laws etc.
  11. ### Enjoy.
  12. sourceweb = "http://github.com/eaydin/cr2fits"
  13. version = "1.0.3"
  14. try :
  15. from copy import deepcopy
  16. import numpy, pyfits, subprocess, sys, re, datetime, math
  17. except :
  18. print("ERROR : Missing some libraries!")
  19. print("Check if you have the following :\n\tnumpy\n\tpyfits\n\tdcraw")
  20. print("For details : %s" % sourceweb)
  21. raise SystemExit
  22. ### --- NETPBMFILE SOURCE CODE --- ###
  23. # Copyright (c) 2011, Christoph Gohlke
  24. # Copyright (c) 2011, The Regents of the University of California
  25. # All rights reserved.
  26. #
  27. # Redistribution and use in source and binary forms, with or without
  28. # modification, are permitted provided that the following conditions are met:
  29. #
  30. # * Redistributions of source code must retain the above copyright
  31. # notice, this list of conditions and the following disclaimer.
  32. # * Redistributions in binary form must reproduce the above copyright
  33. # notice, this list of conditions and the following disclaimer in the
  34. # documentation and/or other materials provided with the distribution.
  35. # * Neither the name of the copyright holders nor the names of any
  36. # contributors may be used to endorse or promote products derived
  37. # from this software without specific prior written permission.
  38. #
  39. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  40. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  41. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  42. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  43. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  44. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  45. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  46. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  47. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  48. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  49. # POSSIBILITY OF SUCH DAMAGE.
  50. __all__ = ['NetpbmFile']
  51. class NetpbmFile(object):
  52. """Read and write Netpbm PAM, PBM, PGM, PPM, files."""
  53. _types = {b'P1': b'BLACKANDWHITE', b'P2': b'GRAYSCALE', b'P3': b'RGB',
  54. b'P4': b'BLACKANDWHITE', b'P5': b'GRAYSCALE', b'P6': b'RGB',
  55. b'P7 332': b'RGB', b'P7': b'RGB_ALPHA'}
  56. def __init__(self, arg=None, **kwargs):
  57. """Initialize instance from filename, open file, or numpy array."""
  58. for attr in ('header', 'magicnum', 'width', 'height', 'maxval',
  59. 'depth', 'tupltypes', '_filename', '_fileid', '_data'):
  60. setattr(self, attr, None)
  61. if arg is None:
  62. self._fromdata([], **kwargs)
  63. elif isinstance(arg, basestring):
  64. self._fileid = open(arg, 'rb')
  65. self._filename = arg
  66. self._fromfile(self._fileid, **kwargs)
  67. elif hasattr(arg, 'seek'):
  68. self._fromfile(arg, **kwargs)
  69. self._fileid = arg
  70. else:
  71. self._fromdata(arg, **kwargs)
  72. def asarray(self, copy=True, cache=False, **kwargs):
  73. """Return image data from file as numpy array."""
  74. data = self._data
  75. if data is None:
  76. data = self._read_data(self._fileid, **kwargs)
  77. if cache:
  78. self._data = data
  79. else:
  80. return data
  81. return deepcopy(data) if copy else data
  82. def write(self, arg, **kwargs):
  83. """Write instance to file."""
  84. if hasattr(arg, 'seek'):
  85. self._tofile(arg, **kwargs)
  86. else:
  87. with open(arg, 'wb') as fid:
  88. self._tofile(fid, **kwargs)
  89. def close(self):
  90. """Close open file. Future asarray calls might fail."""
  91. if self._filename and self._fileid:
  92. self._fileid.close()
  93. self._fileid = None
  94. def __del__(self):
  95. self.close()
  96. def _fromfile(self, fileid):
  97. """Initialize instance from open file."""
  98. fileid.seek(0)
  99. data = fileid.read(4096)
  100. if (len(data) < 7) or not (b'0' < data[1:2] < b'8'):
  101. raise ValueError("Not a Netpbm file:\n%s" % data[:32])
  102. try:
  103. self._read_pam_header(data)
  104. except Exception:
  105. try:
  106. self._read_pnm_header(data)
  107. except Exception:
  108. raise ValueError("Not a Netpbm file:\n%s" % data[:32])
  109. def _read_pam_header(self, data):
  110. """Read PAM header and initialize instance."""
  111. regroups = re.search(
  112. b"(^P7[\n\r]+(?:(?:[\n\r]+)|(?:#.*)|"
  113. b"(HEIGHT\s+\d+)|(WIDTH\s+\d+)|(DEPTH\s+\d+)|(MAXVAL\s+\d+)|"
  114. b"(?:TUPLTYPE\s+\w+))*ENDHDR\n)", data).groups()
  115. self.header = regroups[0]
  116. self.magicnum = b'P7'
  117. for group in regroups[1:]:
  118. key, value = group.split()
  119. setattr(self, unicode(key).lower(), int(value))
  120. matches = re.findall(b"(TUPLTYPE\s+\w+)", self.header)
  121. self.tupltypes = [s.split(None, 1)[1] for s in matches]
  122. def _read_pnm_header(self, data):
  123. """Read PNM header and initialize instance."""
  124. bpm = data[1:2] in b"14"
  125. regroups = re.search(b"".join((
  126. b"(^(P[123456]|P7 332)\s+(?:#.*[\r\n])*",
  127. b"\s*(\d+)\s+(?:#.*[\r\n])*",
  128. b"\s*(\d+)\s+(?:#.*[\r\n])*" * (not bpm),
  129. b"\s*(\d+)\s(?:\s*#.*[\r\n]\s)*)")), data).groups() + (1, ) * bpm
  130. self.header = regroups[0]
  131. self.magicnum = regroups[1]
  132. self.width = int(regroups[2])
  133. self.height = int(regroups[3])
  134. self.maxval = int(regroups[4])
  135. self.depth = 3 if self.magicnum in b"P3P6P7 332" else 1
  136. self.tupltypes = [self._types[self.magicnum]]
  137. def _read_data(self, fileid, byteorder='>'):
  138. """Return image data from open file as numpy array."""
  139. fileid.seek(len(self.header))
  140. data = fileid.read()
  141. dtype = 'u1' if self.maxval < 256 else byteorder + 'u2'
  142. depth = 1 if self.magicnum == b"P7 332" else self.depth
  143. shape = [-1, self.height, self.width, depth]
  144. size = numpy.prod(shape[1:])
  145. if self.magicnum in b"P1P2P3":
  146. data = numpy.array(data.split(None, size)[:size], dtype)
  147. data = data.reshape(shape)
  148. elif self.maxval == 1:
  149. shape[2] = int(math.ceil(self.width / 8))
  150. data = numpy.frombuffer(data, dtype).reshape(shape)
  151. data = numpy.unpackbits(data, axis=-2)[:, :, :self.width, :]
  152. else:
  153. data = numpy.frombuffer(data, dtype)
  154. data = data[:size * (data.size // size)].reshape(shape)
  155. if data.shape[0] < 2:
  156. data = data.reshape(data.shape[1:])
  157. if data.shape[-1] < 2:
  158. data = data.reshape(data.shape[:-1])
  159. if self.magicnum == b"P7 332":
  160. rgb332 = numpy.array(list(numpy.ndindex(8, 8, 4)), numpy.uint8)
  161. rgb332 *= [36, 36, 85]
  162. data = numpy.take(rgb332, data, axis=0)
  163. return data
  164. def _fromdata(self, data, maxval=None):
  165. """Initialize instance from numpy array."""
  166. data = numpy.array(data, ndmin=2, copy=True)
  167. if data.dtype.kind not in "uib":
  168. raise ValueError("not an integer type: %s" % data.dtype)
  169. if data.dtype.kind == 'i' and numpy.min(data) < 0:
  170. raise ValueError("data out of range: %i" % numpy.min(data))
  171. if maxval is None:
  172. maxval = numpy.max(data)
  173. maxval = 255 if maxval < 256 else 65535
  174. if maxval < 0 or maxval > 65535:
  175. raise ValueError("data out of range: %i" % maxval)
  176. data = data.astype('u1' if maxval < 256 else '>u2')
  177. self._data = data
  178. if data.ndim > 2 and data.shape[-1] in (3, 4):
  179. self.depth = data.shape[-1]
  180. self.width = data.shape[-2]
  181. self.height = data.shape[-3]
  182. self.magicnum = b'P7' if self.depth == 4 else b'P6'
  183. else:
  184. self.depth = 1
  185. self.width = data.shape[-1]
  186. self.height = data.shape[-2]
  187. self.magicnum = b'P5' if maxval > 1 else b'P4'
  188. self.maxval = maxval
  189. self.tupltypes = [self._types[self.magicnum]]
  190. self.header = self._header()
  191. def _tofile(self, fileid, pam=False):
  192. """Write Netbm file."""
  193. fileid.seek(0)
  194. fileid.write(self._header(pam))
  195. data = self.asarray(copy=False)
  196. if self.maxval == 1:
  197. data = numpy.packbits(data, axis=-1)
  198. data.tofile(fileid)
  199. def _header(self, pam=False):
  200. """Return file header as byte string."""
  201. if pam or self.magicnum == b'P7':
  202. header = "\n".join(("P7",
  203. "HEIGHT %i" % self.height,
  204. "WIDTH %i" % self.width,
  205. "DEPTH %i" % self.depth,
  206. "MAXVAL %i" % self.maxval,
  207. "\n".join("TUPLTYPE %s" % unicode(i) for i in self.tupltypes),
  208. "ENDHDR\n"))
  209. elif self.maxval == 1:
  210. header = "P4 %i %i\n" % (self.width, self.height)
  211. elif self.depth == 1:
  212. header = "P5 %i %i %i\n" % (self.width, self.height, self.maxval)
  213. else:
  214. header = "P6 %i %i %i\n" % (self.width, self.height, self.maxval)
  215. if sys.version_info[0] > 2:
  216. header = bytes(header, 'ascii')
  217. return header
  218. def __str__(self):
  219. """Return information about instance."""
  220. return unicode(self.header)
  221. if sys.version_info[0] > 2:
  222. basestring = str
  223. unicode = lambda x: str(x, 'ascii')
  224. ### --- END OF NETPBMFILE SOURCE CODE --- ###
  225. ### CR2FITS SOURCE CODE ###
  226. try :
  227. cr2FileName = sys.argv[1]
  228. colorInput = int(sys.argv[2]) # 0=R 1=G 2=B
  229. except :
  230. print("ERROR : You probably don't know how to use it?")
  231. print("./cr2fits.py <cr2filename> <color-index>")
  232. print("The <color-index> can take 3 values:0,1,2 for R,G,B respectively.")
  233. print("Example :\n\t$ ./cr2fits.py myimage.cr2 1")
  234. print("The above example will create 2 outputs.")
  235. print("\tmyimage.ppm : The PPM, which you can delete.")
  236. print("\tmyimage-G.fits : The FITS image in the Green channel, which is the purpose!")
  237. print("For details : http://github.com/eaydin/cr2fits")
  238. print("Version : %s" % version)
  239. raise SystemExit
  240. colors = {0:"Red",1:"Green",2:"Blue"}
  241. colorState = any([True for i in colors.keys() if i == colorInput])
  242. if colorState == False :
  243. print("ERROR : Color value can be set as 0:Red, 1:Green, 2:Blue.")
  244. raise SystemExit
  245. print("Reading file %s...") % cr2FileName
  246. try :
  247. #Converting the CR2 to PPM
  248. p = subprocess.Popen(["dcraw","-6","-j","-W",cr2FileName]).communicate()[0]
  249. #Getting the EXIF of CR2 with dcraw
  250. p = subprocess.Popen(["dcraw","-i","-v",cr2FileName],stdout=subprocess.PIPE)
  251. cr2header = p.communicate()[0]
  252. #Catching the Timestamp
  253. m = re.search('(?<=Timestamp:).*',cr2header)
  254. date1=m.group(0).split()
  255. months = { 'Jan' : 1, 'Feb' : 2, 'Mar' : 3, 'Apr' : 4, 'May' : 5, 'Jun' : 6, 'Jul' : 7, 'Aug' : 8, 'Sep' : 9, 'Oct' : 10, 'Nov' : 11, 'Dec' : 12 }
  256. date = datetime.datetime(int(date1[4]),months[date1[1]],int(date1[2]),int(date1[3].split(':')[0]),int(date1[3].split(':')[1]),int(date1[3].split(':')[2]))
  257. date ='{0:%Y-%m-%d %H:%M:%S}'.format(date)
  258. #Catching the Shutter Speed
  259. m = re.search('(?<=Shutter:).*(?=sec)',cr2header)
  260. shutter = m.group(0).strip()
  261. #Catching the Aperture
  262. m = re.search('(?<=Aperture: f/).*',cr2header)
  263. aperture = m.group(0).strip()
  264. #Catching the ISO Speed
  265. m = re.search('(?<=ISO speed:).*',cr2header)
  266. iso = m.group(0).strip()
  267. #Catching the Focal length
  268. m = re.search('(?<=Focal length: ).*(?=mm)',cr2header)
  269. focal = m.group(0).strip()
  270. #Catching the Original Filename of the cr2
  271. m = re.search('(?<=Filename:).*',cr2header)
  272. original_file = m.group(0).strip()
  273. #Catching the Camera Type
  274. m = re.search('(?<=Camera:).*',cr2header)
  275. camera = m.group(0).strip()
  276. except :
  277. print("ERROR : Something went wrong with dcraw. Do you even have dcraw?")
  278. raise SystemExit
  279. print("Reading the PPM output...")
  280. try :
  281. #Reading the PPM
  282. ppm_name = cr2FileName.split('.')[0] + '.ppm'
  283. im_ppm = NetpbmFile(ppm_name).asarray()
  284. except :
  285. print("ERROR : Something went wrong while reading the PPM file.")
  286. raise SystemExit
  287. print("Extracting %s color channels... (may take a while)" % colors[colorInput])
  288. try :
  289. #Extracting the Green Channel Only
  290. im_green = numpy.zeros((im_ppm.shape[0],im_ppm.shape[1]),dtype=numpy.uint16)
  291. for row in xrange(0,im_ppm.shape[0]) :
  292. for col in xrange(0,im_ppm.shape[1]) :
  293. im_green[row,col] = im_ppm[row,col][colorInput]
  294. except :
  295. print("ERROR : Something went wrong while extracting color channels.")
  296. raise SystemExit
  297. print("Creating the FITS file...")
  298. try :
  299. #Creating the FITS File
  300. hdu = pyfits.PrimaryHDU(im_green)
  301. hdu.header.set('OBSTIME',date)
  302. hdu.header.set('EXPTIME',shutter)
  303. hdu.header.set('APERTUR',aperture)
  304. hdu.header.set('ISO',iso)
  305. hdu.header.set('FOCAL',focal)
  306. hdu.header.set('ORIGIN',original_file)
  307. hdu.header.set('FILTER',colors[colorInput])
  308. hdu.header.set('CAMERA',camera)
  309. hdu.header.add_comment('FITS File Created with cr2fits.py available at %s'%(sourceweb))
  310. hdu.header.add_comment('cr2fits.py version %s'%(version))
  311. hdu.header.add_comment('EXPTIME is in seconds.')
  312. hdu.header.add_comment('APERTUR is the ratio as in f/APERTUR')
  313. hdu.header.add_comment('FOCAL is in mm')
  314. except :
  315. print("ERROR : Something went wrong while creating the FITS file.")
  316. raise SystemExit
  317. print("Writing the FITS file...")
  318. try :
  319. hdu.writeto(cr2FileName.split('.')[0]+"-"+colors[colorInput][0]+'.fits')
  320. except :
  321. print("ERROR : Something went wrong while writing the FITS file. Maybe it already exists?")
  322. raise SystemExit
  323. print("Conversion successful!")