Example #1
0
class Chunk(object):
    """
    when the app is off: 0
    when app is on: 1
    when maze on refresh: 0
    """
    tif = None
    csv = None
    prev_state = None # should be neither True nor False
    open_state = False # but app's initial state was designed to be 1
    def __init__(self, path, u3, did_refresh):
        self.path = path
        self.u3 = u3
        self.did_refresh = did_refresh
        # to have initial chunk
        self.close()
        self.nudge_path()
        self.open()
        self.did_refresh(self.tifpath)
    def tick(self):
        state = self.u3.getFIOState(6)
        if self.prev_state is state: # same state
            if state: # is rising
                pass # self.open_state = True
            else: # is falling
                pass # self.open_state = False
        else: # new state
            # could write simpler code, future me will be suffering
            if state: # is rising
                self.open_state = True
            else: # is falling
                self.open_state = False
                self.refresh()
        self.prev_state = state
    def save(self, frame):
        if not self.open_state:
            return
        self.tif.save(frame)
        self.csv.write(u'{}\n'.format(time.time()))
    def refresh(self):
        self.close()
        self.nudge_path()
        self.open()
        self.did_refresh(self.tifpath)
    def open(self):
        self.tif = TiffWriter(self.tifpath.str, bigtiff=True)
        self.csv = self.csvpath.open('w')
    def nudge_path(self):
        self.tifpath = self.path.joinpath('{}.tif'.format(time.time()))
        self.csvpath = self.path.joinpath('{}.csv'.format(time.time()))
    def close(self):
        if self.tif:
            self.tif.close()
        if self.csv:
            self.csv.close()
        self.is_rising = False
    def did_refresh(self, tifpath):
        pass
Example #2
0
class WriterHandler(BaseHandler):
    def sync_name(self, member, filedir, filename):
        path = ip1_datapath.joinpath(member, filedir)
        if not path.is_dir():
            os.makedirs(path.str)
        self.tifpath = path.joinpath(filename).with_suffix('.tif')
        self.csvpath = path.joinpath(filename).with_suffix('.csv')
        return True  # self.ready()

    def check(self, filename):
        pass

    def ready(self):
        if self.tifpath.is_file() or self.csvpath.is_file():
            raise Exception(
                'Filename already exists. Please provide new one...')
        else:
            return True

    def register(self):
        super(WriterHandler, self).register()
        self.ready_at = time.time()

    def enter(self):
        print 'enter'
        self.tif = TiffWriter(self.tifpath.str, bigtiff=True)
        self.csv = self.csvpath.open('w')

    def exposure_end(self, frame, _ts):
        if self.svc.bypass:
            return
        ts = time.time() - self.ready_at
        self.tif.save(frame)
        # self.tif.save(frame, extratags=[(
        #     306, 's', 0, str(ts), False
        # )])
        self.csv.write(u'{}\n'.format(ts))

    def exit(self):
        print 'exit'
        self.tif.close()
        self.csv.close()
Example #3
0
def analysis_txt(widget,
                 imagelist,
                 roiname,
                 outlist,
                 expand_pixel,
                 roi_enlarge_pixel,
                 expand_f=0,
                 meth=None):

    num = int(len(outlist))
    """
    我们新建了一个QProgressDialog对象progress,设置它的标题、标签、增加取消的按钮。
    """
    progress = QProgressDialog(widget)
    progress.setWindowTitle("请稍等")
    progress.setLabelText("正在操作...")
    progress.setCancelButtonText("取消")
    """
    如果任务的预期持续时间小于minimumDuration,则对话框根本不会出现。这样可以防止弹出对话框,快速完成任务。对于预期超过minimumDuration的任务,对话框将在minimumDuration时间之后或任何进度设置后立即弹出。如果设置为0,则只要设置任何进度,将始终显示对话框。 默认值为4000毫秒,即4秒。
    """
    progress.setMinimumDuration(5)  #此属性保留对话框出现之前必须通过的时间。
    """
    此属性保留由模态小部件阻止的窗口。
    这个属性只对Windows有意义。 模态小部件防止其他窗口中的小部件获取输入。 该属性的值控制在窗口小部件可见时阻止哪些窗口。 窗口可见时更改此属性无效; 您必须首先hide()小部件,然后再次show()。
    默认情况下,此属性为Qt.NonModal。
    """
    progress.setWindowModality(Qt.WindowModal)
    """
    由上面我们知道:使用setMinimum() 和setMaximum() 或构造函数来设置操作中的“steps”数量,并在操作进行时调用setValue()。setRange(0,num)就是设置其最小和最大值,这里最小值0,最大值num,num是根据输入框中的数字确定的。
    """
    progress.setRange(0, num)
    """
    setValue()该属性持有当前的进度。要使进度对话框按预期的方式工作,您应该首先将此属性设置为QProgressDialog的最大最小值, 您可以在中间调用setValue()任意次数。
    通过wasCanceled()判断我们是否按下取消按钮,如果按下则提示失败。若for循环顺利结束,执行else后的语句,表明成功
    """

    roi2 = ImagejRoi.fromfile(roiname)
    outfilename = outlist[0] + "_shift.zip"
    if os.path.exists(outfilename):
        os.remove(outfilename)
    print('outfile:', outfilename)
    zip1 = zipfile.ZipFile(outfilename, 'w')
    zip1.close()
    #os.mkdir(os.path.join(pathway,name))
    for roi in roi2:
        roi.tofile(outfilename)
    img = Image.open(imagelist[0])
    img = np.asarray(img, dtype=np.float32)
    img_ori = img.copy()
    imgs = []

    path, filename = os.path.split(outlist[0])
    mergefile = os.path.join(path, "_merge.tif")
    tifroifile = os.path.join(path, "batch_sequence.txt")
    img_ori = draw_roi_onimage(roi2, img_ori)
    imgs.append(np.array(img_ori, dtype=np.uint16))

    count = 1
    for imagefile, outname, templatefile in zip(imagelist[1:], outlist[1:],
                                                imagelist[:-1]):
        progress.setValue(count)
        if progress.wasCanceled():
            QMessageBox.warning(widget, "提示", "操作失败")
            break
        count += 1

        roi2 = ImagejRoi.fromfile(outfilename)
        image_template = Image.open(templatefile)
        image_template = np.asarray(image_template, dtype=np.float32)

        print('processing file:', imagefile)
        img = Image.open(imagefile)
        print(img.format, img.size, img.mode)
        img = np.asarray(img, dtype=np.float32)
        img_ori = img.copy()
        img = match_histograms(img, image_template, multichannel=False)
        height, width = img.shape
        outofborder = 0

        # align first
        alignx, aligny = align.caculate_shift(image_template, img)

        alignx = stats.mode(alignx)[0][0]
        aligny = stats.mode(aligny)[0][0]
        print('alignx', -alignx, 'align_y', -aligny)
        img = np.roll(img, aligny, axis=0)
        img = np.roll(img, alignx, axis=1)

        # padding edge ,top,bottom,left,right
        # expand pixel
        # print(image_template.shape)
        image_template = cv2.copyMakeBorder(image_template,
                                            expand_pixel,
                                            expand_pixel,
                                            expand_pixel,
                                            expand_pixel,
                                            borderType=cv2.BORDER_REPLICATE)
        img = cv2.copyMakeBorder(img,
                                 expand_pixel,
                                 expand_pixel,
                                 expand_pixel,
                                 expand_pixel,
                                 borderType=cv2.BORDER_REPLICATE)
        # print(image_template.shape)
        for roi in roi2:
            a, b, c, d = roi.left, roi.bottom, roi.right, roi.top
            if a < 0 or b < 0 or c >= width or d >= height:
                print('err', a, b, c, d)

            roi.left = roi.left + expand_pixel
            roi.top = roi.top + expand_pixel
            roi.right = roi.right + expand_pixel
            roi.bottom = roi.bottom + expand_pixel

        roi_corners, roi_imgs, roi_offsets = _get_template_img_from_roi(
            image_template,
            roi2,
            expand_pixel=roi_enlarge_pixel,
            expand_f=expand_f)

        # match template
        pre_image = image_template
        roi_corners, roi_imgs, roi_offsets = _get_roiimg_from_match(
            img, pre_image, roi_corners, roi_imgs, roi_offsets, roi2,
            expand_pixel, expand_f, meth)
        pre_image = Image.open(imagefile)
        pre_image = np.asarray(pre_image)

        # write new roi
        outfilename = outname + "_shift.zip"
        if os.path.exists(outfilename):
            os.remove(outfilename)
        print('outfile:', outfilename)
        zip1 = zipfile.ZipFile(outfilename, 'w')
        zip1.close()
        #os.mkdir(os.path.join(pathway,name))
        for roi in roi2:
            shiftx, shifty = roi_offsets[roi.name][1]  # 0 is roi shift
            shiftx = int(shiftx)
            shifty = int(shifty)
            roi.left = roi.left + shiftx - expand_pixel - alignx
            roi.top = roi.top + shifty - expand_pixel - aligny
            roi.right = roi.right + shiftx - expand_pixel - alignx
            roi.bottom = roi.bottom + shifty - expand_pixel - aligny
            roi.tofile(outfilename)
        img_ori = draw_roi_onimage(roi2, img_ori)
        imgs.append(np.array(img_ori, dtype=np.uint16))
    else:
        progress.setValue(num)
        QMessageBox.information(widget, "提示", "操作成功")
    # write roi and image merge
    tif = TiffWriter(mergefile)
    for img in imgs:
        tif.write(img, contiguous=True)
    tif.close()
    # write batch txt for caculate roi
    with open(tifroifile, "w") as f:
        for imagefile, outname in zip(imagelist, outlist):
            outfilename = outname + "_shift.zip"
            f.write(imagefile + "\n")
            f.write(outfilename + "\n")
laser = TopticaiBeam(port="COM1")

# initialise buffer as a queue
image_buffer = Queue()

# configure camera, pass the buffer queue and enable.
camera.set_client(image_buffer)
camera.exposure_time = exposure_seconds
camera.set_trigger(TriggerType.SOFTWARE, TriggerMode.ONCE)
camera.enable()

# configure laser
laser.power = power_level
laser.set_trigger(TriggerType.HIGH, TriggerMode.BULB)
laser.enable()

# main loop to collect images.
for i in range(n_repeats):
    camera.trigger()
    time.sleep(interval_seconds)

# shutdown hardware devices
laser.shutdown()
camera.shutdown()

# write out image data to a file.
writer = TiffWriter("data.tif")
for i in range(n_repeats):
    writer.save(image_buffer.get())
writer.close()