Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def setUp(self):
"""Download files"""
self.dataFile = UtilsTest.getimage(self.__class__.dataFile)
self.poniFile = UtilsTest.getimage(self.__class__.poniFile)
self.ai = pyFAI.load(self.poniFile)
# self.ai.mask = None
self.data = fabio.open(self.dataFile).data
self.mask = self.data < 0
def test_quantile(self):
if not os.path.exists(self.exe):
print("Error with executable: %s" % self.exe)
print(os.listdir(os.path.dirname(self.exe)))
p = subprocess.call([sys.executable, self.exe, "--quiet", "-q", "0.2-0.8", "-o", self.outfile] + self.image_files,
shell=False, env=self.env)
if p:
l = [sys.executable, self.exe, "--quiet", "-q", "0.2-0.8", "-o", self.outfile] + self.image_files
logger.error(os.linesep + (" ".join(l)))
env = "Environment:"
for k, v in self.env.items():
env += "%s %s: %s" % (os.linesep, k, v)
logger.error(env)
self.assertEqual(p, 0, msg="pyFAI-average return code %i != 0" % p)
self.assert_(numpy.allclose(fabio.open(self.outfile).data, self.res),
"pyFAI-average with quantiles gives good results")
parser.add_option("-e", "--energy", dest="energy", type="float",
help="energy of the X-Ray beam in keV (hc=%skeV.A)" % hc, default=None)
parser.add_option("-w", "--wavelength", dest="wavelength", type="float",
help="wavelength of the X-Ray beam in Angstrom", default=None)
(options, args) = parser.parse_args()
if options.version:
print("Check calibrarion: version %s" % pyFAI.version)
sys.exit(0)
if options.mask is not None:
self.mask = fabio.open(options.mask).data
if len(args) > 0:
f = args[0]
if os.path.isfile(f):
self.data = fabio.open(f).data
else:
print("Please enter diffraction inages as arguments")
sys.exit(1)
self.data = [f for f in args if os.path.isfile(f)]
self.ai = pyFAI.load(options.poni)
if options.wavelength:
self.ai.wavelength = 1e-10 * options.wavelength
elif options.energy:
self.ai.wavelength = 1e-10 * hc / options.energy
# else:
if options.ponifile and to_process:
integrator = pyFAI.load(options.ponifile)
if to_process:
first = to_process[0]
fabimg = fabio.open(first)
integrator.detector.guess_binning(fabimg.data)
if options.wavelength:
integrator.wavelength = options.wavelength * 1e-10
elif options.energy:
integrator.wavelength = hc / options.energy * 1e-10
if options.mask and os.path.exists(options.mask): # override with the command line mask
integrator.maskfile = options.mask
if options.dark and os.path.exists(options.dark): # set dark current
integrator.darkcurrent = fabio.open(options.dark).data
if options.flat and os.path.exists(options.flat): # set Flat field
integrator.flatfield = fabio.open(options.flat).data
if options.method:
method = options.method
else:
if len(to_process) > 5:
method = "full_csr"
else:
method = "splitpixel"
print(integrator)
print("Mask: %s\tMethod: %s" % (integrator.maskfile, method))
for afile in to_process:
sys.stdout.write("Integrating %s --> " % afile)
outfile = os.path.splitext(afile)[0] + options.ext
t0 = time.time()
def __init__(self, poni, img):
self.ponifile = poni
self.ai = pyFAI.load(poni)
self.img = fabio.open(img)
self.r = None
self.I = None
self.resynth = None
self.delta = None
# works for scalar and array
data = data[()]
elif url.scheme() == "fabio":
import fabio
data_slice = url.data_slice()
if data_slice is None:
data_slice = (0, )
if data_slice is None or len(data_slice) != 1:
raise ValueError("Fabio slice expect a single frame, but %s found" % data_slice)
index = data_slice[0]
if not isinstance(index, int):
raise ValueError("Fabio slice expect a single integer, but %s found" % data_slice)
try:
fabio_file = fabio.open(url.file_path())
except Exception:
logger.debug("Error while opening %s with fabio", url.file_path(), exc_info=True)
raise IOError("Error while opening %s with fabio (use debug for more information)" % url.path())
if fabio_file.nframes == 1:
if index != 0:
raise ValueError("Only a single frame available. Slice %s out of range" % index)
data = fabio_file.data
else:
data = fabio_file.getframe(index).data
# There is no explicit close
fabio_file = None
else:
raise ValueError("Scheme '%s' not supported" % url.scheme())
def load_fabio(self, filename):
"""
Loads an image using the fabio library.
:param filename: path to the image file to be loaded
:return: dictionary with image_data and image_data_fabio, None if unsuccessful
"""
try:
img_data_fabio = fabio.open(filename)
img_data = img_data_fabio.data[::-1]
return {"img_data_fabio": img_data_fabio, "img_data": img_data}
except (IOError, fabio.fabioutils.NotGoodReader):
return None
def process_one_file(self, filename):
"""
:param filename: name of the input filename
:param idx: index of file
"""
if self.ai is None:
self.setup_ai()
if self.dataset is None:
self.makeHDF5()
t = time.time()
fimg = fabio.open(filename)
self.process_one_frame(fimg.data)
if fimg.nframes > 1:
for i in range(fimg.nframes - 1):
fimg = fimg.next()
self.process_one_frame(fimg.data)
t -= time.time()
print("Processing %30s took %6.1fms (%i frames)" %
(os.path.basename(filename), -1000.0 * t, fimg.nframes))
self.timing.append(-t)
self.processed_file.append(filename)
def get_data(self):
try:
import fabio
except ImportError:
raise NeXusError("Please install the 'fabio' module")
self.import_file = self.get_filename()
im = fabio.open(self.import_file)
z = NXfield(im.data, name='z')
y = NXfield(range(z.shape[0]), name='y')
x = NXfield(range(z.shape[1]), name='x')
note = NXnote(type='text/plain', file_name=self.import_file)
note.data = im.header.pop('_array_data.header_contents', '')
note.description = im.header.pop('_array_data.header_convention', '')
header = NXcollection()
for k, v in im.header.items():
header[k] = v
return NXentry(NXdata(z,(y,x), CBF_header=note, header=header))
cv2.imshow('step?', cv2.resize((img * 255.0 / img.max()).astype(np.uint8), (0, 0), fx=.5, fy=.5))
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
i = 0
for imgpath in glob.glob(os.path.join("../../saxswaxs/AgBs", '*.edf')):
i += 1
if i < 0:
continue
print "Opening", imgpath
# read image
img = fabio.open(imgpath).data
outputimg = img.copy()
# print new center approximation; Add demo=True to see it work!
circle = center_approx(img, demo=True)
if circle is not None:
outputimg = np.uint8(outputimg)
outputimg = cv2.cvtColor(outputimg, cv2.COLOR_GRAY2BGR)
cv2.circle(outputimg, (int(circle[0]), int(circle[1])), int(circle[2]), (255, 0, 0), 3)
cv2.circle(outputimg, (int(circle[0]), int(circle[1])), 10, (255, 0, 0), 10)
cv2.imwrite(imgpath + "_center.png", cv2.resize(outputimg, (0, 0), fx=.3, fy=.3))