• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python image.Image类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pylinac.core.image.Image的典型用法代码示例。如果您正苦于以下问题:Python Image类的具体用法?Python Image怎么用?Python Image使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Image类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_multiples

    def test_multiples(self):
        paths = [dcm_path, dcm_path, dcm_path]
        img = Image.load_multiples(paths)
        self.assertIsInstance(img, DicomImage)

        # test non-superimposable images
        paths = [dcm_path, tif_path]
        with self.assertRaises(ValueError):
            Image.load_multiples(paths)
开发者ID:darcymason,项目名称:pylinac,代码行数:9,代码来源:test_image.py


示例2: _find_HU_slice

    def _find_HU_slice(self):
        """Using a brute force search of the images, find the median HU linearity slice.

        This method walks through all the images and takes a collapsed circle profile where the HU
        linearity ROIs are. If the profile contains both low (<800) and high (>800) HU values and most values are the same
        (i.e. its not an artifact, then
        it can be assumed it is an HU linearity slice. The median of all applicable slices is the
        center of the HU slice.

        Returns
        -------
        int
            The middle slice of the HU linearity module.
        """
        hu_slices = []
        for image_number in range(self.num_images):
            image = self.images[:, :, image_number]
            slice = Slice(self, Image.from_array(image))
            try:
                slice.find_phan_center()
            except ValueError:  # a slice without the phantom in view
                continue
            else:
                circle_prof = CollapsedCircleProfile(slice.phan_center, radius=120/self.fov_ratio)
                circle_prof.get_profile(image, width_ratio=0.05, num_profiles=5)
                prof = circle_prof.y_values
                # determine if the profile contains both low and high values and that most values are the same
                if (np.percentile(prof, 2) < 800) and (np.percentile(prof, 98) > 800) and (np.percentile(prof, 80) - np.percentile(prof, 30) < 40):
                    hu_slices.append(image_number)

        center_hu_slice = int(np.median(hu_slices))
        return center_hu_slice
开发者ID:oblasi,项目名称:pylinac,代码行数:32,代码来源:cbct.py


示例3: test_combine_multiples

    def test_combine_multiples(self):
        bad_img_path = [dcm_path, img_path]
        self.assertRaises(AttributeError, Image.from_multiples, bad_img_path)

        good_img_path = [img_path, img_path]
        combined_img = Image.from_multiples(good_img_path)
        self.assertIsInstance(combined_img, Image)
开发者ID:spidersaint,项目名称:pylinac,代码行数:7,代码来源:test_image.py


示例4: test_all

 def test_all(self):
     futures = []
     start = time.time()
     with concurrent.futures.ProcessPoolExecutor() as exec:
         for pdir, sdir, files in os.walk(self.image_bank_dir):
             for file in files:
                 filepath = osp.join(pdir, file)
                 try:
                     Image.load(filepath)
                 except:
                     pass
                 else:
                     future = exec.submit(run_star, filepath)
                     futures.append(future)
         for future in concurrent.futures.as_completed(futures):
             print(future.result())
     end = time.time() - start
     print('Processing of {} files took {}s'.format(len(futures), end))
开发者ID:darcymason,项目名称:pylinac,代码行数:18,代码来源:_test_all_starshots.py


示例5: load_image

    def load_image(self, filepath):
        """Load the image via the file path.

        Parameters
        ----------
        filepath : str
            Path to the file to be loaded.
        """
        self.image = Image(filepath)
开发者ID:oblasi,项目名称:pylinac,代码行数:9,代码来源:starshot.py


示例6: _find_bb

    def _find_bb(self):
        """Find the BB within the radiation field. Iteratively searches for a circle-like object
        by lowering a low-pass threshold value until found.

        Returns
        -------
        Point
            The weighted-pixel value location of the BB.
        """

        def is_boxlike(array):
            """Whether the binary object's dimensions are symmetric, i.e. box-like"""
            ymin, ymax, xmin, xmax = get_bounding_box(array)
            y = abs(ymax - ymin)
            x = abs(xmax - xmin)
            if x > max(y * 1.05, y+3) or x < min(y * 0.95, y-3):
                return False
            return True

        # get initial starting conditions
        hmin = np.percentile(self.array, 5)
        hmax = self.array.max()
        spread = hmax - hmin
        max_thresh = hmax

        # search for the BB by iteratively lowering the low-pass threshold value until the BB is found.
        found = False
        while not found:
            try:
                lower_thresh = hmax - spread / 2
                t = np.where((max_thresh > self) & (self >= lower_thresh), 1, 0)
                labeled_arr, num_roi = ndimage.measurements.label(t)
                roi_sizes, bin_edges = np.histogram(labeled_arr, bins=num_roi + 1)
                bw_node_cleaned = np.where(labeled_arr == np.argsort(roi_sizes)[-3], 1, 0)
                expected_fill_ratio = np.pi / 4
                actual_fill_ratio = get_filled_area_ratio(bw_node_cleaned)
                if (expected_fill_ratio * 1.1 < actual_fill_ratio) or (actual_fill_ratio < expected_fill_ratio * 0.9):
                    raise ValueError
                if not is_boxlike(bw_node_cleaned):
                    raise ValueError
            except (IndexError, ValueError):
                max_thresh -= 0.05 * spread
                if max_thresh < hmin:
                    raise ValueError("Unable to locate the BB")
            else:
                found = True

        # determine the center of mass of the BB
        inv_img = Image.load(self.array)
        inv_img.invert()
        x_arr = np.abs(np.average(bw_node_cleaned, weights=inv_img, axis=0))
        x_com = SingleProfile(x_arr).fwxm_center(interpolate=True)
        y_arr = np.abs(np.average(bw_node_cleaned, weights=inv_img, axis=1))
        y_com = SingleProfile(y_arr).fwxm_center(interpolate=True)
        return Point(x_com, y_com)
开发者ID:darcymason,项目名称:pylinac,代码行数:55,代码来源:winston_lutz.py


示例7: load_multiple_images

    def load_multiple_images(self, filepath_list):
        """Load multiple images via the file path.

        .. versionadded:: 0.5.1

        Parameters
        ----------
        filepath_list : sequence
            An iterable sequence of filepath locations.
        """
        self.image = Image.from_multiples(filepath_list)
开发者ID:gitter-badger,项目名称:pylinac,代码行数:11,代码来源:starshot.py


示例8: __init__

    def __init__(self, settings):
        super().__init__(settings)
        self.scale_by_FOV()
        self.image = Image.from_array(combine_surrounding_slices(self.settings.images, self.settings.SR_slice_num, mode='max'))

        self.LP_MTF = OrderedDict()  # holds lp:mtf data
        for idx, radius in enumerate(self.radius2profs):
            c = SR_Circle_ROI(idx, self.image.array, radius=radius)
            self.add_ROI(c)

        super().find_phan_center()
开发者ID:victorgabr,项目名称:pylinac,代码行数:11,代码来源:cbct.py


示例9: load_image

    def load_image(self, filepath):
        """Load the image via the file path.

        Parameters
        ----------
        filepath : str
            Path to the file to be loaded.
        """
        self.image = Image(filepath)
        # apply filter if it's a large image to reduce noise
        if self.image.shape[0] > 1100:
            self.image.median_filter(0.002)
开发者ID:gitter-badger,项目名称:pylinac,代码行数:12,代码来源:starshot.py


示例10: __init__

 def __init__(self, filepath=None):
     """
     Parameters
     ----------
     filepath : None, str
         If None, image must be loaded later.
         If a str, path to the image file.
     """
     if filepath is not None and is_valid_file(filepath):
         self.image = Image.load(filepath)
     else:
         self.image = np.zeros((1,1))
开发者ID:darcymason,项目名称:pylinac,代码行数:12,代码来源:flatsym.py


示例11: load_multiple_images

    def load_multiple_images(self, path_list):
        """Load and superimpose multiple images.

        .. versionadded:: 0.9

        Parameters
        ----------
        path_list : iterable
            An iterable of path locations to the files to be loaded/combined.
        """
        self.image = Image.load_multiples(path_list, method='mean')
        self._check_for_noise()
        self.image.check_inversion()
开发者ID:darcymason,项目名称:pylinac,代码行数:13,代码来源:picketfence.py


示例12: load_image

    def load_image(self, file_path, filter=None):
        """Load the image

        Parameters
        ----------
        file_path : str
            Path to the image file.
        filter : int, None
            If None (default), no filtering will be done to the image.
            If an int, will perform median filtering over image of size *filter*.
        """
        self.image = Image(file_path)
        if isinstance(filter, int):
            self.image.array = spfilt.median_filter(self.image.array, size=filter)
        self._clear_attrs()
开发者ID:gitter-badger,项目名称:pylinac,代码行数:15,代码来源:picketfence.py


示例13: load_image

    def load_image(self, file_path, filter=None):
        """Load the image

        Parameters
        ----------
        file_path : str
            Path to the image file.
        filter : int, None
            If None (default), no filtering will be done to the image.
            If an int, will perform median filtering over image of size *filter*.
        """
        self.image = Image(file_path)
        if isinstance(filter, int):
            self.image.median_filter(size=filter)
        self._check_for_noise()
        self.image.check_inversion()
开发者ID:Jothy,项目名称:RTQA,代码行数:16,代码来源:PicketFenceSumImg.py


示例14: test_open

    def test_open(self):
        """Test the open class method."""
        # load a tif file
        img = Image(img_path)
        self.assertEqual(img.im_type, IMAGE)

        # load a dicom file
        img2 = Image(dcm_path)
        self.assertEqual(img2.im_type, DICOM)

        # try loading a bad file
        bad_file = osp.abspath(__file__)
        self.assertRaises(TypeError, Image, bad_file)

        # not a valid parameter
        bad_input = 3.5
        self.assertRaises(TypeError, Image, bad_input)

        # load an array
        dcm = dicom.read_file(dcm_path)
        img = Image.from_array(dcm.pixel_array)
        self.assertEqual(img.im_type, ARRAY)
开发者ID:spidersaint,项目名称:pylinac,代码行数:22,代码来源:test_image.py


示例15: load_image

    def load_image(self, file_path, im_type=None):
        """Load the image directly by the file path.

        Parameters
        ----------
        file_path : str, file-like object
            The path to the DICOM image or I/O stream.
        im_type : {'open', 'mlcs', None}
            Specifies what image type is being loaded in. If None, will try to determine the type from the name.
            The name must have 'open' or 'dmlc' in the name.
        """
        img = Image.load(file_path)
        if im_type is not None:
            if _is_open_type(im_type):
                self.image_open = img
            elif _is_dmlc_type(im_type):
                self.image_dmlc = img
        else:
            # try to guess type by the name
            imtype = self._try_to_guess_image_type(osp.basename(file_path))
            if imtype is not None:
                self.load_image(file_path, imtype)
            else:
                raise ValueError("Image type was not given nor could it be determined from the path name. Please enter and image type.")
开发者ID:darcymason,项目名称:pylinac,代码行数:24,代码来源:vmat.py


示例16: load_demo_image

 def load_demo_image(self):
     """Load the demo image."""
     demo_file = osp.join(osp.dirname(__file__), 'demo_files', 'flatsym', 'flatsym_demo.dcm')
     self.image = Image.load(demo_file)
开发者ID:darcymason,项目名称:pylinac,代码行数:4,代码来源:flatsym.py


示例17: Test_Image_Methods

class Test_Image_Methods(unittest.TestCase):

    def setUp(self):
        self.img = Image(img_path)
        self.dcm = Image(dcm_path)
        small_array = np.arange(42).reshape(6,7)
        self.sm_arr = Image.from_array(small_array)

    def test_remove_edges(self):
        """Remove the edges from a pixel array."""
        crop = 15
        orig_shape = self.img.shape
        orig_dpi = self.img.dpi
        self.img.remove_edges(crop)
        new_shape = self.img.shape
        new_dpi = self.img.dpi
        self.assertEqual(new_shape[0]+crop*2, orig_shape[0])
        # ensure original metadata is still the same
        self.assertEqual(new_dpi, orig_dpi)

    def test_median_filter(self):
        filter_size = 3
        self.sm_arr.median_filter(filter_size)
        self.assertEqual(self.sm_arr.array[0, 0], 1)
        filter_size = 0.03
        self.sm_arr.median_filter(filter_size)

        self.assertRaises(ValueError, self.img.median_filter, 1.1)

    def test_ground(self):
        old_min_val = copy.copy(self.dcm.array.min())
        ground_val = self.dcm.ground()
        self.assertEqual(old_min_val, ground_val)
        # test that array was also changed
        self.assertAlmostEqual(self.dcm.array.min(), 0)

    def test_resize(self):
        new_size = (200, 300)
        self.img.resize(new_size)
        self.assertEqual(self.img.shape, new_size)

    def test_invert(self):
        self.img.invert()

    def test_dist2edge_min(self):
        dist = self.sm_arr.dist2edge_min(Point(1,3))
        self.assertEqual(dist, 1)

        dist = self.sm_arr.dist2edge_min((1,3))
        self.assertEqual(dist, 1)

    def test_center(self):
        self.assertIsInstance(self.img.center, Point)
        img_known_center = Point(512, 1702)
        dcm_known_center = Point(512, 384)
        self.assertEqual(self.img.center.x, img_known_center.x)
        self.assertEqual(self.dcm.center.y, dcm_known_center.y)

    def test_SID(self):
        self.assertEqual(self.dcm.SID, 1050)
        self.assertRaises(TypeError, setattr, self.dcm, 'SID', '105')

    def test_combine_multiples(self):
        bad_img_path = [dcm_path, img_path]
        self.assertRaises(AttributeError, Image.from_multiples, bad_img_path)

        good_img_path = [img_path, img_path]
        combined_img = Image.from_multiples(good_img_path)
        self.assertIsInstance(combined_img, Image)

    def test_plot(self):
        self.img.plot()  # shouldn't raise
开发者ID:spidersaint,项目名称:pylinac,代码行数:72,代码来源:test_image.py


示例18: PicketFence

class PicketFence:
    """A class used for analyzing EPID images where radiation strips have been formed by the
    MLCs. The strips are assumed to be parallel to one another and normal to the image edge;
    i.e. a "left-right" or "up-down" orientation is assumed. Further work could follow up by accounting
    for any angle.

    Attributes
    ----------
    pickets: list
        Holds :class:`~pylinac.picketfence.Picket` objects.
    image: :class:`~pylinac.core.image.Image` object.

    Examples
    --------
    Run the demo::
        >>> PicketFence().run_demo()

    Typical session:
        >>> img_path = r"C:/QA/June/PF.dcm"  # the EPID image
        >>> mypf = PicketFence(img_path)
        >>> mypf.analyze(tolerance=0.5, action_tolerance=0.3)
        >>> print(mypf.return_results())
        >>> mypf.plot_analyzed_image()
    """
    def __init__(self, filename=None, filter=None):
        self.pickets = []
        self._action_lvl = None
        if filename is not None:
            self.load_image(filename, filter)

    def _clear_attrs(self):
        """Clear attributes; necessary when new image loaded or analysis done on same image."""
        self.pickets = []
        self._action_lvl = None

    @property
    def passed(self):
        """Boolean specifying if all MLC positions were within tolerance."""
        for picket in self.pickets:
            for meas in picket.mlc_meas:
                if not meas.passed:
                    return False
        return True

    @property
    def percent_passing(self):
        """Return the percentage of MLC positions under tolerance."""
        num = 0
        num_pass = 0
        for picket in self.pickets:
            num += len(picket._error_array)
            num_pass += sum(picket._error_array < picket._tolerance)
        pct_pass = 100 * num_pass / num
        return pct_pass

    @property
    def max_error(self):
        """Return the maximum error found."""
        max_error = 0
        for idx, picket in enumerate(self.pickets):
            if picket.max_error > max_error:
                max_error = picket.max_error
        return max_error

    @property
    def max_error_picket(self):
        """Return the picket number where the maximum error occured."""
        max_error = 0
        where_at = 0
        for idx, picket in enumerate(self.pickets):
            if picket.max_error > max_error:
                max_error = picket.max_error
                where_at = idx
        return where_at

    @property
    def max_error_leaf(self):
        """Return the leaf that had the maximum error."""
        picket = self.pickets[self.max_error_picket]
        return np.argmax(picket._error_array)

    @property
    def abs_median_error(self):
        """Return the median error found."""
        median_error = []
        for picket in self.pickets:
            median_error.append(picket.abs_median_error)
        return max(median_error)

    @property
    def _action_lvl_set(self):
        if self._action_lvl is not None:
            return True
        else:
            return False

    @property
    def num_pickets(self):
        """Return the number of pickets determined."""
        return len(self.pickets)
#.........这里部分代码省略.........
开发者ID:gitter-badger,项目名称:pylinac,代码行数:101,代码来源:picketfence.py


示例19: film

class Starshot:
    """Class that can determine the wobble in a "starshot" image, be it gantry, collimator,
        couch or MLC. The image can be DICOM or a scanned film (TIF, JPG, etc).

    Attributes
    ----------
    image : :class:`~pylinac.core.image.Image`
    circle_profile : :class:`~pylinac.starshot.StarProfile`
    lines : :class:`~pylinac.starshot.LineManager`
    wobble : :class:`~pylinac.starshot.Wobble`

    Examples
    --------
    Run the demo:
        >>> Starshot().run_demo()

    Typical session:
        >>> img_path = r"C:/QA/Starshots/Coll.jpeg"
        >>> mystar = Starshot(img_path)
        >>> mystar.analyze()
        >>> print(mystar.return_results())
        >>> mystar.plot_analyzed_image()
    """
    def __init__(self, filepath=None):
        """
        Parameters
        ----------
        filepath : str, optional
            The path to the image file. If None, the image must be loaded later.
        """
        self.wobble = Wobble()
        self.tolerance = Tolerance(1, 'pixels')
        if filepath is not None:
            self.load_image(filepath)

    @classmethod
    def from_url(cls, url):
        """Instantiate from a URL.

        .. versionadded:: 0.7.1
        """
        obj = cls()
        obj.load_url(url)
        return obj

    def load_url(self, url):
        """Load from a URL.

        .. versionadded:: 0.7.1
        """
        try:
            import requests
        except ImportError:
            raise ImportError("Requests is not installed; cannot get the log from a URL")
        response = requests.get(url)
        if response.status_code != 200:
            raise ConnectionError("Could not connect to the URL")
        stream = BytesIO(response.content)
        self.load_image(stream)

    @classmethod
    def from_demo_image(cls):
        """Construct a Starshot instance and load the demo image.

        .. versionadded:: 0.6
        """
        obj = cls()
        obj.load_demo_image()
        return obj

    def load_demo_image(self):
        """Load the starshot demo image."""
        demo_file = osp.join(osp.dirname(__file__), 'demo_files', 'starshot', '10X_collimator.tif')
        self.load_image(demo_file)

    def load_image(self, filepath):
        """Load the image via the file path.

        Parameters
        ----------
        filepath : str
            Path to the file to be loaded.
        """
        self.image = Image(filepath)

    @classmethod
    def from_multiple_images(cls, filepath_list):
        """Construct a Starshot instance and load in and combine multiple images.

        .. versionadded:: 0.6

        Parameters
        ----------
        filepath_list : iterable
            An iterable of file paths to starshot images that are to be superimposed.
        """
        obj = cls()
        obj.load_multiple_images(filepath_list)
        return obj

#.........这里部分代码省略.........
开发者ID:oblasi,项目名称:pylinac,代码行数:101,代码来源:starshot.py


示例20: setUp

 def setUp(self):
     self.img = Image.load(tif_path)
     self.dcm = Image.load(dcm_path)
     array = np.arange(42).reshape(6, 7)
     self.arr = Image.load(array)
开发者ID:darcymason,项目名称:pylinac,代码行数:5,代码来源:test_image.py



注:本文中的pylinac.core.image.Image类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python vmat.VMAT类代码示例发布时间:2022-05-25
下一篇:
Python test.make_test_client函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap