Skip to main content

How to pair images with matching header information

In [ ]:
#Astronomical images usually contains headers, where information about the image is stored.
#One thing I had to do in my project is to choose for each image in one data set I, another image from another data set II that were taken close in time.

#For that I have to do the following:

#- For each image in data set I, I extract the observation time information from the header
#- I loop though images from data set II and extract the same information
#- For each pair I compute the time difference using the function explained in the earlier post
#- I choose the image from data set II with minimum time difference from the image of data set I

import pyfits
import numpy as np
import datetime
import os

def diff_time(t1, t2):

 h1, m1, s1 = t1.hour, t1.minute, t1.second
 h2, m2, s2 = t2.hour, t2.minute, t2.second
 t1_secs = s1 + (60*m1)
 t2_secs = s2 + (60*m2)
 return (t2_secs - t1_secs)



path1 = '...'   #path of dataset I
path2 = '....'  #path of dataset II
list1 = os.listdir(path1)
list2 = os.listdir(path2)

for file1 in list1:
  im1 = pyfits.open(path1+file1)
  im1_header = im1[0].header
  im1_datetime = im1_header['DATE_OBS']
  im1_time = datetime.datetime.strptime(im1_datetime,'%Y-%m-%dT%H:%M:%S.%f').time()  #this will extract only the observation time 


  TIME = np.zeros(len(list2))  #here we are making those arrays to store the obs. time of images from data set II to later choose the minumum
  IND = ["" for ind in range(len(list2))]  #these are the corresponding image files from dataset II
  n = 0
  for file2 in list2:

       im2 = pyfits.open(path2+file2)
       im2_header = im2[0].header
       im2_datetime = im2_header['DATE_OBS']
       im2_time = datetime.datetime.strptime(im2_datetime,'%Y-%m-%dT%H:%M:%S.%f').time() 
       d = diff_time(im1_time,im2_time) #calling the diff_time function
       TIME[n] = abs(d)
       IND[n] = file2
       n = n+1
  im2_min = IND[np.where(TIME==TIME.min())[0][0]]