I am using an astropy package called WCS.all_world2pix in order to convert many coordinates in degrees to pixel coordinates on an image. While running this on many pairs of coordinates, I eventually came across an error which stopped my program from running. Here is the code leading up the error, and the error itself:
import glob
import numpy as np
import re
from astropy.io import fits
from astropy.wcs import WCS
initial_data, centroid_coords = [], []
image_files = glob.glob('/home/username/Desktop/myfolder/*.fits')
for image in image_files:
img_data = np.nan_to_num(fits.getdata(image))
obj_num = int(re.search('2\d{6}', image).group(0))
count_num = int(re.search('_(\d+)_', image).group(1))
obj_index = int(np.where(good_data == obj_num)[0])
count_index = int(np.where(np.array(all_counters[obj_index]) == count_num)[0])
ra, dec = pos_match[obj_index][count_index]
w = WCS(image)
x, y = w.all_world2pix(ra, dec, 0)
initial_data.append(img_data)
centroid_coords.append((float(x), float(y)))
The error:
x, y = w.all_world2pix(ra, dec, 0)
File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1827, in all_world2pix
'input', *args, **kwargs
File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1269, in _array_converter
return _return_list_of_arrays(axes, origin)
File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1225, in _return_list_of_arrays
output = func(xy, origin)
File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1826, in <lambda>
quiet=quiet),
File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1812, in _all_world2pix
slow_conv=ind, divergent=inddiv)
astropy.wcs.wcs.NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy.
After 2 iterations, the solution is diverging at least for one input point.
I would just like to be able to skip over those images that cause this error. But I'm unsure how to handle this as an exception, since it's not a usual Type/Value/SyntaxError, etc...
As it's going through my loop, when/if this error occurs I'd just like it to continue to the next element in the loop without appending anything for the one that caused the error. Something like this is what I have in mind:
for image in image_files:
img_data = np.nan_to_num(fits.getdata(image))
obj_num = int(re.search('2\d{6}', image).group(0))
count_num = int(re.search('_(\d+)_', image).group(1))
obj_index = int(np.where(good_data == obj_num)[0])
count_index = int(np.where(np.array(all_counters[obj_index]) == count_num)[0])
ra, dec = pos_match[obj_index][count_index]
w = WCS(image)
try:
x, y = w.all_world2pix(ra, dec, 0)
initial_data.append(img_data)
centroid_coords.append((float(x), float(y)))
except: # skip images where coordinates fail to converge
# Not sure how to identify the error here
continue
How can I handle this exception? I've never actually dealt with these before, so any help is appreciated. Thanks!