Repository: SBU-BMI/wsinfer (language: python)

Issue:
use Apache 2.0 license



Discussion / hints:

Fix patch:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index afe6331..158f26d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -69,7 +69,7 @@ jobs:
           test -f results/run_metadata_*.json
           test -f results/patches/JP2K-33003-1.h5
           test -f results/model-outputs/JP2K-33003-1.csv
-          test $(wc -l < results/model-outputs/JP2K-33003-1.csv) -eq 653
+          test $(wc -l < results/model-outputs/JP2K-33003-1.csv) -eq 675
 
   # This is run on multiple operating systems.
   test-package:
@@ -105,7 +105,7 @@ jobs:
           test -f results/run_metadata_*.json
           test -f results/patches/JP2K-33003-1.h5
           test -f results/model-outputs/JP2K-33003-1.csv
-          test $(wc -l < results/model-outputs/JP2K-33003-1.csv) -eq 653
+          test $(wc -l < results/model-outputs/JP2K-33003-1.csv) -eq 675
       # FIXME: tissue segmentation has different outputs on Windows. The patch sizes
       # are the same but the coordinates found are different.
       - name: Run 'wsinfer run' on Windows
@@ -119,7 +119,7 @@ jobs:
           Test-Path -Path results/run_metadata_*.json -PathType Leaf
           Test-Path -Path results/patches/JP2K-33003-1.h5 -PathType Leaf
           Test-Path -Path results/model-outputs/JP2K-33003-1.csv -PathType Leaf
-          # test $(python -c "print(sum(1 for _ in open('results/model-outputs/JP2K-33003-1.csv')))") -eq 653
+          # test $(python -c "print(sum(1 for _ in open('results/model-outputs/JP2K-33003-1.csv')))") -eq 675
 
   style-and-types:
     runs-on: ubuntu-latest
diff --git a/LICENSE b/LICENSE
index f288702..13df0da 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,674 +1,201 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-                            Preamble
-
-  The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
-  The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works.  By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.  We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors.  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
-  To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights.  Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received.  You must make sure that they, too, receive
-or can get the source code.  And you must show them these terms so they
-know their rights.
-
-  Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
-  For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software.  For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
-  Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so.  This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software.  The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable.  Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products.  If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
-  Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary.  To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-                       TERMS AND CONDITIONS
-
-  0. Definitions.
-
-  "This License" refers to version 3 of the GNU General Public License.
-
-  "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
-  "The Program" refers to any copyrightable work licensed under this
-License.  Each licensee is addressed as "you".  "Licensees" and
-"recipients" may be individuals or organizations.
-
-  To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy.  The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
-  A "covered work" means either the unmodified Program or a work based
-on the Program.
-
-  To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy.  Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
-  To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies.  Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
-  An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License.  If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
-  1. Source Code.
-
-  The "source code" for a work means the preferred form of the work
-for making modifications to it.  "Object code" means any non-source
-form of a work.
-
-  A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
-  The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form.  A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
-  The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities.  However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work.  For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
-  The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
-  The Corresponding Source for a work in source code form is that
-same work.
-
-  2. Basic Permissions.
-
-  All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met.  This License explicitly affirms your unlimited
-permission to run the unmodified Program.  The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work.  This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
-  You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force.  You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright.  Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
-  Conveying under any other circumstances is permitted solely under
-the conditions stated below.  Sublicensing is not allowed; section 10
-makes it unnecessary.
-
-  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-  No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
-  When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
-  4. Conveying Verbatim Copies.
-
-  You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
-  You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
-  5. Conveying Modified Source Versions.
-
-  You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
-    a) The work must carry prominent notices stating that you modified
-    it, and giving a relevant date.
-
-    b) The work must carry prominent notices stating that it is
-    released under this License and any conditions added under section
-    7.  This requirement modifies the requirement in section 4 to
-    "keep intact all notices".
-
-    c) You must license the entire work, as a whole, under this
-    License to anyone who comes into possession of a copy.  This
-    License will therefore apply, along with any applicable section 7
-    additional terms, to the whole of the work, and all its parts,
-    regardless of how they are packaged.  This License gives no
-    permission to license the work in any other way, but it does not
-    invalidate such permission if you have separately received it.
-
-    d) If the work has interactive user interfaces, each must display
-    Appropriate Legal Notices; however, if the Program has interactive
-    interfaces that do not display Appropriate Legal Notices, your
-    work need not make them do so.
-
-  A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit.  Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
-  6. Conveying Non-Source Forms.
-
-  You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
-    a) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by the
-    Corresponding Source fixed on a durable physical medium
-    customarily used for software interchange.
-
-    b) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by a
-    written offer, valid for at least three years and valid for as
-    long as you offer spare parts or customer support for that product
-    model, to give anyone who possesses the object code either (1) a
-    copy of the Corresponding Source for all the software in the
-    product that is covered by this License, on a durable physical
-    medium customarily used for software interchange, for a price no
-    more than your reasonable cost of physically performing this
-    conveying of source, or (2) access to copy the
-    Corresponding Source from a network server at no charge.
-
-    c) Convey individual copies of the object code with a copy of the
-    written offer to provide the Corresponding Source.  This
-    alternative is allowed only occasionally and noncommercially, and
-    only if you received the object code with such an offer, in accord
-    with subsection 6b.
-
-    d) Convey the object code by offering access from a designated
-    place (gratis or for a charge), and offer equivalent access to the
-    Corresponding Source in the same way through the same place at no
-    further charge.  You need not require recipients to copy the
-    Corresponding Source along with the object code.  If the place to
-    copy the object code is a network server, the Corresponding Source
-    may be on a different server (operated by you or a third party)
-    that supports equivalent copying facilities, provided you maintain
-    clear directions next to the object code saying where to find the
-    Corresponding Source.  Regardless of what server hosts the
-    Corresponding Source, you remain obligated to ensure that it is
-    available for as long as needed to satisfy these requirements.
-
-    e) Convey the object code using peer-to-peer transmission, provided
-    you inform other peers where the object code and Corresponding
-    Source of the work are being offered to the general public at no
-    charge under subsection 6d.
-
-  A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
-  A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling.  In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage.  For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product.  A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
-  "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source.  The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
-  If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information.  But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
-  The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed.  Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
-  Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
-  7. Additional Terms.
-
-  "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law.  If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
-  When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it.  (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.)  You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
-  Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
-    a) Disclaiming warranty or limiting liability differently from the
-    terms of sections 15 and 16 of this License; or
-
-    b) Requiring preservation of specified reasonable legal notices or
-    author attributions in that material or in the Appropriate Legal
-    Notices displayed by works containing it; or
-
-    c) Prohibiting misrepresentation of the origin of that material, or
-    requiring that modified versions of such material be marked in
-    reasonable ways as different from the original version; or
-
-    d) Limiting the use for publicity purposes of names of licensors or
-    authors of the material; or
-
-    e) Declining to grant rights under trademark law for use of some
-    trade names, trademarks, or service marks; or
-
-    f) Requiring indemnification of licensors and authors of that
-    material by anyone who conveys the material (or modified versions of
-    it) with contractual assumptions of liability to the recipient, for
-    any liability that these contractual assumptions directly impose on
-    those licensors and authors.
-
-  All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10.  If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term.  If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
-  If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
-  Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
-  8. Termination.
-
-  You may not propagate or modify a covered work except as expressly
-provided under this License.  Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
-  However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
-  Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
-  Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License.  If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
-  9. Acceptance Not Required for Having Copies.
-
-  You are not required to accept this License in order to receive or
-run a copy of the Program.  Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance.  However,
-nothing other than this License grants you permission to propagate or
-modify any covered work.  These actions infringe copyright if you do
-not accept this License.  Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
-  10. Automatic Licensing of Downstream Recipients.
-
-  Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License.  You are not responsible
-for enforcing compliance by third parties with this License.
-
-  An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations.  If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
-  You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License.  For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
-  11. Patents.
-
-  A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based.  The
-work thus licensed is called the contributor's "contributor version".
-
-  A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version.  For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
-  Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
-  In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement).  To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
-  If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients.  "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
-  If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
-  A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License.  You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
-  Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
-  12. No Surrender of Others' Freedom.
-
-  If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all.  For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
-  13. Use with the GNU Affero General Public License.
-
-  Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work.  The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
-  14. Revised Versions of this License.
-
-  The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-  Each version is given a distinguishing version number.  If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation.  If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
-  If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
-  Later license versions may give you additional or different
-permissions.  However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
-  15. Disclaimer of Warranty.
-
-  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. Limitation of Liability.
-
-  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
-  17. Interpretation of Sections 15 and 16.
-
-  If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software: you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation, either version 3 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <https://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
-  If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
-    <program>  Copyright (C) <year>  <name of author>
-    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
-  You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<https://www.gnu.org/licenses/>.
-
-  The GNU General Public License does not permit incorporating your program
-into proprietary programs.  If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.  But first, please read
-<https://www.gnu.org/licenses/why-not-lgpl.html>.
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright 2023 Jakub Kaczmarzyk
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/setup.cfg b/setup.cfg
index d49db10..f164066 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -6,7 +6,6 @@ author_email = jakub.kaczmarzyk@stonybrookmedicine.edu
 description = Run patch-based classification on pathology whole slide images.
 long_description = file: README.md
 long_description_content_type = text/markdown
-license = GNU General Public License v3 (GPLv3)
 license_file = LICENSE
 classifiers =
     Development Status :: 4 - Beta
@@ -14,7 +13,7 @@ classifiers =
     Intended Audience :: Developers
     Intended Audience :: Healthcare Industry
     Intended Audience :: Science/Research
-    License :: OSI Approved :: GNU General Public License v3 (GPLv3)
+    License :: OSI Approved :: Apache Software License
     Operating System :: OS Independent
     Programming Language :: Python :: 3
     Programming Language :: Python :: 3 :: Only
@@ -38,6 +37,7 @@ install_requires =
     pandas
     pillow
     pyyaml
+    scikit-image>=0.20.0
     shapely
     tifffile
     tiffslide
@@ -101,6 +101,8 @@ ignore_missing_imports = True
 ignore_missing_imports = True
 [mypy-shapely.*]
 ignore_missing_imports = True
+[mypy-skimage.morphology]
+ignore_missing_imports = True
 [mypy-tifffile]
 ignore_missing_imports = True
 [mypy-zarr.storage]
diff --git a/wsinfer/cli/infer.py b/wsinfer/cli/infer.py
index 795a7a5..067bf74 100644
--- a/wsinfer/cli/infer.py
+++ b/wsinfer/cli/infer.py
@@ -24,7 +24,7 @@
 
 from ..modellib import models
 from ..modellib.run_inference import run_inference
-from ..patchlib.create_patches_fp import create_patches
+from ..patchlib import segment_and_patch_directory_of_slides
 
 
 def _num_cpus() -> int:
@@ -350,18 +350,20 @@ def run(
 
     click.secho("\nFinding patch coordinates...\n", fg="green")
 
-    create_patches(
-        source=str(wsi_dir),
-        save_dir=str(results_dir),
-        patch_size=model_obj.config.patch_size_pixels,
-        patch_spacing=model_obj.config.spacing_um_px,
-        seg=True,
-        patch=True,
-        # Stitching is a bottleneck when using tiffslide.
-        # TODO: figure out why this is...
-        stitch=False,
-        # FIXME: allow customization of this preset
-        preset="tcga.csv",
+    # FIXME: add presets for different tissue types?
+
+    segment_and_patch_directory_of_slides(
+        wsi_dir=wsi_dir,
+        save_dir=results_dir,
+        patch_size_px=model_obj.config.patch_size_pixels,
+        patch_spacing_um_px=model_obj.config.spacing_um_px,
+        thumbsize=(2048, 2048),
+        # TODO: these can be made arguments to the CLI.
+        median_filter_size=7,
+        binary_threshold=7,
+        closing_kernel_size=6,
+        min_object_size_um2=200**2,
+        min_hole_size_um2=190**2,
     )
 
     click.secho("\nRunning model inference.\n", fg="green")
diff --git a/wsinfer/cli/patch.py b/wsinfer/cli/patch.py
index 105b0fe..6f24edb 100644
--- a/wsinfer/cli/patch.py
+++ b/wsinfer/cli/patch.py
@@ -1,76 +1,100 @@
 from __future__ import annotations
 
-from typing import Optional
+from pathlib import Path
 
 import click
 
-from ..patchlib.create_patches_fp import create_patches as _create_patches
+from ..patchlib import segment_and_patch_directory_of_slides
 
 
 @click.command()
 @click.option(
-    "--source",
+    "-i",
+    "--wsi-dir",
+    type=click.Path(exists=True, file_okay=False, path_type=Path, resolve_path=True),
     required=True,
-    type=click.Path(exists=True),
-    help="patch to directory containing whole slide image files",
+    help="Directory containing whole slide images. This directory can *only* contain"
+    " whole slide images.",
 )
-@click.option("--step-size", default=None, type=int, help="Step size for patching.")
-@click.option("--patch-size", required=True, type=int, help="Patch size in pixels.")
-@click.option("--auto-skip/--no-auto-skip", default=True, help="Skip existing outputs.")
 @click.option(
-    "--save-dir",
+    "-o",
+    "--results-dir",
+    type=click.Path(file_okay=False, path_type=Path, resolve_path=True),
     required=True,
-    type=click.Path(),
-    help="Directory to save processed data",
+    help="Directory to store patch results. If directory exists, will skip"
+    " whole slides for which outputs exist.",
 )
+@click.option("--patch-size-px", required=True, type=int, help="Patch size in pixels.")
 @click.option(
-    "--preset",
-    default="tcga.csv",
-    help="Predefined profile of default segmentation and filter parameters (.csv)",
+    "--patch-spacing-um-px",
+    required=True,
+    type=float,
+    help="Physical spacing of the patch in micrometers per pixel.",
 )
 @click.option(
-    "--process-list", help="Name of list of images to process with parameters (.csv)"
+    "--thumbsize",
+    default=(2048, 2048),
+    type=(int, int),
+    help="The size of the slide thumbnail (in pixels) used for tissue segmentation."
+    " The aspect ratio is preserved, and the longest side will have length"
+    " max(thumbsize).",
 )
 @click.option(
-    "--patch-spacing",
-    required=True,
-    type=float,
-    help="Patch spacing in micrometers per pixel.",
+    "--median-filter-size",
+    default=7,
+    type=click.IntRange(min=3),
+    help="The kernel size for median filtering. Must be greater than 1 and odd.",
+)
+@click.option(
+    "--binary-threshold",
+    default=7,
+    type=click.IntRange(min=1),
+    help="The threshold for image binarization.",
 )
 @click.option(
-    "--segmentation-dir",
-    type=click.Path(),
-    help="Directory containing .pkl files with tissue segmentations",
+    "--closing-kernel-size",
+    default=6,
+    type=click.IntRange(min=1),
+    help="The kernel size for binary closing (morphological operation).",
+)
+@click.option(
+    "--min-object-size-um2",
+    default=200**2,
+    type=click.FloatRange(min=0),
+    help="The minimum size of an object to keep during tissue detection. If a"
+    " contiguous object is smaller than this area, it replaced with background."
+    " The default is 200um x 200um. The units of this argument are microns squared.",
+)
+@click.option(
+    "--min-hole-size-um2",
+    default=190**2,
+    type=click.FloatRange(min=0),
+    help="The minimum size of a hole to keep as a hole. If a hole is smaller than this"
+    " area, it is filled with foreground. The default is 190um x 190um. The units of"
+    " this argument are microns squared.",
 )
 def patch(
-    source: str,
-    step_size: Optional[int],
-    patch_size: int,
-    auto_skip: bool,
-    save_dir: str,
-    preset: Optional[str],
-    process_list: Optional[str],
-    patch_spacing: float,
-    segmentation_dir: Optional[str],
+    wsi_dir: str,
+    results_dir: str,
+    patch_size_px: int,
+    patch_spacing_um_px: float,
+    thumbsize: tuple[int, int],
+    median_filter_size: int,
+    binary_threshold: int,
+    closing_kernel_size: int,
+    min_object_size_um2: float,
+    min_hole_size_um2: float,
 ):
-    """Patchify a directory of whole slide images."""
-
-    print("create_patches_fp.py  Copyright (C) 2022  Mahmood Lab")
-    print("This program comes with ABSOLUTELY NO WARRANTY.")
-    print("This is free software, and you are welcome to redistribute it")
-    print("under certain conditions.")
-
-    _create_patches(
-        source=source,
-        step_size=step_size,
-        patch_size=patch_size,
-        patch_spacing=patch_spacing,
-        save_dir=save_dir,
-        patch=True,
-        seg=True,
-        stitch=True,
-        auto_skip=auto_skip,
-        preset=preset,
-        process_list=process_list,
-        segmentation_dir=segmentation_dir,
+    """Patch a directory of whole slide iamges."""
+    segment_and_patch_directory_of_slides(
+        wsi_dir=wsi_dir,
+        save_dir=results_dir,
+        patch_size_px=patch_size_px,
+        patch_spacing_um_px=patch_spacing_um_px,
+        thumbsize=thumbsize,
+        median_filter_size=median_filter_size,
+        binary_threshold=binary_threshold,
+        closing_kernel_size=closing_kernel_size,
+        min_object_size_um2=min_object_size_um2,
+        min_hole_size_um2=min_hole_size_um2,
     )
diff --git a/wsinfer/modellib/models.py b/wsinfer/modellib/models.py
index bef488c..529c992 100644
--- a/wsinfer/modellib/models.py
+++ b/wsinfer/modellib/models.py
@@ -5,7 +5,6 @@
 from typing import Callable
 from typing import Union
 
-
 import torch
 import wsinfer_zoo
 from wsinfer_zoo.client import HFModelTorchScript
diff --git a/wsinfer/patchlib/README.md b/wsinfer/patchlib/README.md
deleted file mode 100644
index fd87df3..0000000
--- a/wsinfer/patchlib/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# patchlib from CLAM
-
-This code is a slightly modified version of the patching utilities in [`mahmoodlab/CLAM`](https://github.com/mahmoodlab/CLAM/tree/6fbcaa38d79e69f83dd463527093848fa4aa5091), licensed under GPL-3.0.
-
-The modifications include the addition of a `--spacing` parameter to enable the creation of patches at a particular whole slide image resolution.
diff --git a/wsinfer/patchlib/__init__.py b/wsinfer/patchlib/__init__.py
index 215c3f7..7e1b75e 100644
--- a/wsinfer/patchlib/__init__.py
+++ b/wsinfer/patchlib/__init__.py
@@ -1,22 +1,236 @@
-# Create tissue mask and patch a whole slide image.
-# Copyright (C) 2022  Mahmood Lab
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <https://www.gnu.org/licenses/>.
-#
-# Modified by Jakub Kaczmarzyk (@kaczmarj on GitHub)
-# - add --patch_spacing command line arg to request a patch size at a particular
-#   spacing. The patch coordinates are calculated at the base (highest) resolution.
-# - format code with black
-
 from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Sequence
+
+import cv2 as cv
+import h5py
+import numpy as np
+import numpy.typing as npt
+from PIL import Image
+
+from ..wsi import WSI
+from ..wsi import get_avg_mpp
+from .patch import get_multipolygon_from_binary_arr
+from .patch import get_nonoverlapping_patch_coordinates_within_polygon
+from .segment import segment_tissue
+
+logger = logging.getLogger(__name__)
+
+MASKS_DIR = "masks"
+PATCHES_DIR = "patches"
+
+
+def segment_and_patch_one_slide(
+    slide_path: str | Path,
+    save_dir: str | Path,
+    patch_size_px: int,
+    patch_spacing_um_px: float,
+    thumbsize: tuple[int, int] = (2048, 2048),
+    median_filter_size: int = 7,
+    binary_threshold: int = 7,
+    closing_kernel_size: int = 6,
+    min_object_size_um2: float = 200**2,
+    min_hole_size_um2: float = 190**2,
+) -> None:
+    """Get patch coordinates."""
+
+    save_dir = Path(save_dir).resolve()
+    slide_path = Path(slide_path).resolve()
+    slide_prefix = slide_path.stem
+
+    logger.info(f"Segmenting and patching slide {slide_path}")
+    logger.info(f"Using prefix as slide ID: {slide_prefix}")
+
+    patch_path = save_dir / PATCHES_DIR / f"{slide_prefix}.h5"
+    mask_path = save_dir / MASKS_DIR / f"{slide_prefix}.jpg"
+
+    # End early if outputs exist.
+    if patch_path.exists() and mask_path.exists():
+        logger.info("Patch output and mask output files already exist")
+        logger.info(f"patch_path={patch_path}")
+        logger.info(f"mask_path={mask_path}")
+        return None
+
+    slide = WSI(slide_path)
+    mpp = get_avg_mpp(slide_path)
+    logger.info(f"Slide has WxH {slide.dimensions} and MPP={mpp}")
+
+    logger.info(
+        f"Requested patch size of {patch_size_px} px at {patch_spacing_um_px} um/px"
+    )
+    logger.info(
+        f"Scaling patch size by {patch_spacing_um_px / mpp} for patch coordinates at"
+        f" level 0 (MPP={mpp}) | patch_spacing_um_px / mpp"
+        f" ({patch_spacing_um_px} / {mpp})"
+    )
+    patch_size = round(patch_size_px * patch_spacing_um_px / mpp)
+    logger.info(f"Final patch size is {patch_size}")
+
+    # Segment tissue into a binary mask.
+    if len(thumbsize) != 2:
+        raise ValueError(f"Length of 'thumbsize' must be 2 but got {len(thumbsize)}")
+    thumb: Image.Image = slide.get_thumbnail(thumbsize)
+    # TODO: allow the min hole size and min object size to be set in physical units.
+
+    # thumb has ~12 MPP.
+    thumb_mpp = (mpp * (np.array(slide.dimensions) / thumb.size)).mean()
+    logger.info(f"Thumbnail has WxH {thumb.size} and MPP={thumb_mpp}")
+    thumb_mpp_squared: float = thumb_mpp**2
+
+    # (pixels2 / micron2) * micron2 = pixels2
+    min_object_size_px: int = round(min_object_size_um2 / thumb_mpp_squared)
+    min_hole_size_px: int = round(min_hole_size_um2 / thumb_mpp_squared)
+
+    logger.info(
+        f"Transformed minimum object size to {min_object_size_px} pixel area in"
+        " thumbnail"
+    )
+    logger.info(
+        f"Transformed minimum hole size to {min_hole_size_px} pixel area in thumbnail"
+    )
+
+    arr = segment_tissue(
+        np.asarray(thumb),
+        median_filter_size=median_filter_size,
+        binary_threshold=binary_threshold,
+        closing_kernel_size=closing_kernel_size,
+        min_object_size_px=min_object_size_px,
+        min_hole_size_px=min_hole_size_px,
+    )
+    if not np.issubdtype(arr.dtype, np.bool_):
+        raise TypeError(
+            f"expected the segmentation array to be boolean dtype but got {arr.dtype}"
+        )
+
+    # Create a polygon of the binary tissue mask.
+    scale: tuple[float, float] = (
+        slide.dimensions[0] / thumb.size[0],
+        slide.dimensions[1] / thumb.size[1],
+    )
+    polygon, contours, hierarchy = get_multipolygon_from_binary_arr(
+        arr.astype("uint8") * 255, scale=scale
+    )
+
+    # Get the coordinates of patches inside the tissue polygon.
+    slide_width, slide_height = slide.dimensions
+    half_patch_size = round(patch_size / 2)
+
+    # Nx4 --> N x (minx, miny, width, height)
+    coords = get_nonoverlapping_patch_coordinates_within_polygon(
+        slide_width=slide_width,
+        slide_height=slide_height,
+        patch_size=patch_size,
+        half_patch_size=half_patch_size,
+        polygon=polygon,
+    )
+    logger.info(f"Found {len(coords)} patches within tissue")
+
+    # Save coordinates to HDF5.
+    patch_path.parent.mkdir(exist_ok=True, parents=True)
+    save_hdf5(
+        path=patch_path,
+        coords=coords,
+        patch_size=patch_size,
+        patch_spacing_um_px=patch_spacing_um_px,
+        compression="gzip",
+    )
+
+    # Save thumbnail with drawn contours.
+    logger.info(f"Writing tissue thumbnail with contours to disk: {mask_path}")
+    mask_path.parent.mkdir(exist_ok=True, parents=True)
+    img = draw_contours_on_thumbnail(thumb, contours=contours, hierarchy=hierarchy)
+    img.thumbnail((1024, 1024), resample=Image.Resampling.LANCZOS)
+    img.save(mask_path)
+
+    return None
+
+
+def save_hdf5(
+    path: str | Path,
+    coords: npt.NDArray[np.int_],
+    patch_size: int,
+    patch_spacing_um_px: float,
+    compression: str | None = "gzip",
+):
+    """Write patch coordinates to HDF5 file.
+
+    This is designed to be interoperable with HDF5 files created by CLAM.
+    """
+    logger.info(f"Writing coordinates to disk: {path}")
+    logger.info(f"Coordinates have shape {coords.shape}")
+
+    if coords.ndim != 2:
+        raise ValueError(f"coords must have 2 dimensions but got {coords.ndim}")
+    if coords.shape[1] != 2:
+        raise ValueError(f"length of second axis must be 2 but got {coords.shape[1]}")
+
+    with h5py.File(path, "w") as f:
+        dset = f.create_dataset("/coords", data=coords, compression=compression)
+        dset.attrs["patch_size"] = patch_size
+        dset.attrs["patch_level"] = 0
+        dset.attrs["patch_spacing_um_px"] = patch_spacing_um_px
+
+
+def draw_contours_on_thumbnail(
+    thumb: Image.Image,
+    contours: Sequence[npt.NDArray[np.int_]],
+    hierarchy: npt.NDArray[np.int_],
+) -> Image.Image:
+    assert hierarchy.ndim == 3
+    assert hierarchy.shape[0] == 1
+    assert hierarchy.shape[2] == 4
+    assert len(contours) == hierarchy.shape[1]
+
+    # We assume the hierarchy was made with RETR_CCOMP.
+    contour_is_external = (hierarchy[0, :, 3] < 0).tolist()
+    external = [c for c, external in zip(contours, contour_is_external) if external]
+    hole = [c for c, external in zip(contours, contour_is_external) if not external]
+
+    img = np.array(thumb)
+    # Colors are BGR.
+    cv.drawContours(img, external, -1, (0, 255, 255), 7)
+    cv.drawContours(img, hole, -1, (255, 255, 0), 7)
+
+    return Image.fromarray(img).convert("RGB")
+
+
+def segment_and_patch_directory_of_slides(
+    wsi_dir: str | Path,
+    save_dir: str | Path,
+    patch_size_px: int,
+    patch_spacing_um_px: float,
+    thumbsize: tuple[int, int] = (2048, 2048),
+    median_filter_size: int = 7,
+    binary_threshold: int = 7,
+    closing_kernel_size: int = 6,
+    min_object_size_um2: float = 200**2,
+    min_hole_size_um2: float = 190**2,
+) -> None:
+    """Get patch coordinates. for a directory of slides."""
+
+    wsi_dir = Path(wsi_dir)
+    slide_paths = sorted(wsi_dir.glob("*"))
+
+    # NOTE: we could use multi-processing here but then the logs would get
+    # discombobulated.
+    for i, slide_path in enumerate(slide_paths):
+        print(f"Slide {i+1} of {len(slide_paths)} ({(i+1)/len(slide_paths):.2%})")
+        try:
+            segment_and_patch_one_slide(
+                slide_path=slide_path,
+                save_dir=save_dir,
+                patch_size_px=patch_size_px,
+                patch_spacing_um_px=patch_spacing_um_px,
+                thumbsize=thumbsize,
+                median_filter_size=median_filter_size,
+                binary_threshold=binary_threshold,
+                closing_kernel_size=closing_kernel_size,
+                min_object_size_um2=min_object_size_um2,
+                min_hole_size_um2=min_hole_size_um2,
+            )
+        except Exception as e:
+            logger.error(f"Failed to segment and patch slide\n{slide_path}", exc_info=e)
+
+    return None
diff --git a/wsinfer/patchlib/create_patches_fp.py b/wsinfer/patchlib/create_patches_fp.py
deleted file mode 100644
index dc8125b..0000000
--- a/wsinfer/patchlib/create_patches_fp.py
+++ /dev/null
@@ -1,481 +0,0 @@
-# Create tissue mask and patch a whole slide image.
-# Copyright (C) 2022  Mahmood Lab
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <https://www.gnu.org/licenses/>.
-#
-# Modified by Jakub Kaczmarzyk (@kaczmarj on GitHub)
-# - add --patch_spacing command line arg to request a patch size at a particular
-#   spacing. The patch coordinates are calculated at the base (highest) resolution.
-# - format code with black
-# - add segmentation_dir option to use pre-existing tissue masks
-
-"""Create tissue mask and patch a whole slide image.
-Copyright (C) 2022  Mahmood Lab
-
-Modified by Jakub Kaczmarzyk.
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-"""
-
-from __future__ import annotations
-
-# other imports
-import os
-import pathlib
-import time
-from typing import Optional
-
-import numpy as np
-import pandas as pd
-
-from wsinfer.errors import CannotReadSpacing
-from wsinfer.patchlib.wsi_core.batch_process_utils import initialize_df
-
-# internal imports
-from wsinfer.patchlib.wsi_core.WholeSlideImage import WholeSlideImage
-from wsinfer.patchlib.wsi_core.wsi_utils import StitchCoords
-from wsinfer.wsi import get_avg_mpp
-
-_script_path = pathlib.Path(__file__).resolve().parent
-
-
-def stitching(file_path, wsi_object, downscale=64):
-    start = time.time()
-    heatmap = StitchCoords(
-        file_path,
-        wsi_object,
-        downscale=downscale,
-        bg_color=(0, 0, 0),
-        alpha=-1,
-        draw_grid=False,
-    )
-    total_time = time.time() - start
-
-    return heatmap, total_time
-
-
-def segment(WSI_object, seg_params=None, filter_params=None, mask_file=None):
-    # Start Seg Timer
-    start_time = time.time()
-    # Use segmentation file
-    if mask_file is not None:
-        WSI_object.initSegmentation(mask_file)
-    # Segment
-    else:
-        WSI_object.segmentTissue(**seg_params, filter_params=filter_params)
-
-    # Stop Seg Timers
-    seg_time_elapsed = time.time() - start_time
-    return WSI_object, seg_time_elapsed
-
-
-def patching(WSI_object, **kwargs):
-    # Start Patch Timer
-    start_time = time.time()
-
-    # Patch
-    file_path = WSI_object.process_contours(**kwargs)
-
-    # Stop Patch Timer
-    patch_time_elapsed = time.time() - start_time
-    return file_path, patch_time_elapsed
-
-
-def seg_and_patch(
-    source,
-    save_dir,
-    patch_save_dir,
-    mask_save_dir,
-    stitch_save_dir,
-    patch_size: int = 256,
-    step_size: Optional[int] = None,
-    seg_params={
-        "seg_level": -1,
-        "sthresh": 8,
-        "mthresh": 7,
-        "close": 4,
-        "use_otsu": False,
-        "keep_ids": "none",
-        "exclude_ids": "none",
-    },
-    filter_params={"a_t": 100, "a_h": 16, "max_n_holes": 8},
-    vis_params={"vis_level": -1, "line_thickness": 500},
-    patch_params={"use_padding": True, "contour_fn": "four_pt"},
-    patch_level=0,
-    use_default_params=False,
-    seg=False,
-    save_mask=True,
-    stitch=False,
-    patch=False,
-    auto_skip=True,
-    process_list=None,
-    patch_spacing=None,
-    segmentation_dir=None,
-):
-    slides = sorted(os.listdir(source))
-    slides = [slide for slide in slides if os.path.isfile(os.path.join(source, slide))]
-    if process_list is None:
-        df = initialize_df(slides, seg_params, filter_params, vis_params, patch_params)
-
-    else:
-        df = pd.read_csv(process_list)
-        df = initialize_df(df, seg_params, filter_params, vis_params, patch_params)
-
-    mask = df["process"] == 1
-    process_stack = df[mask]
-
-    total = len(process_stack)
-
-    legacy_support = "a" in df.keys()
-    if legacy_support:
-        print("detected legacy segmentation csv file, legacy support enabled")
-        df = df.assign(
-            **{
-                "a_t": np.full((len(df)), int(filter_params["a_t"]), dtype=np.uint32),
-                "a_h": np.full((len(df)), int(filter_params["a_h"]), dtype=np.uint32),
-                "max_n_holes": np.full(
-                    (len(df)), int(filter_params["max_n_holes"]), dtype=np.uint32
-                ),
-                "line_thickness": np.full(
-                    (len(df)), int(vis_params["line_thickness"]), dtype=np.uint32
-                ),
-                "contour_fn": np.full((len(df)), patch_params["contour_fn"]),
-            }
-        )
-
-    seg_times = 0.0
-    patch_times = 0.0
-    stitch_times = 0.0
-
-    orig_patch_size = patch_size
-    orig_step_size = step_size
-
-    for i in range(total):
-        df.to_csv(os.path.join(save_dir, "process_list_autogen.csv"), index=False)
-        idx = process_stack.index[i]
-        slide = process_stack.loc[idx, "slide_id"]
-        print("\n\nprogress: {:.1%}, {}/{}".format(i / total, i + 1, total))
-        print("processing {}".format(slide))
-
-        df.loc[idx, "process"] = 0
-        slide_id, _ = os.path.splitext(slide)
-
-        if auto_skip and os.path.isfile(os.path.join(patch_save_dir, slide_id + ".h5")):
-            print("{} already exist in destination location, skipped".format(slide_id))
-            df.loc[idx, "status"] = "already_exist"
-            continue
-
-        # Inialize WSI
-        full_path = os.path.join(source, slide)
-        # Some slide files might be malformed and unreadable. Skip them.
-        try:
-            WSI_object = WholeSlideImage(full_path)
-        except Exception:
-            print(f"Failed to load slide, skipping {full_path}")
-            continue
-
-        if use_default_params:
-            current_vis_params = vis_params.copy()
-            current_filter_params = filter_params.copy()
-            current_seg_params = seg_params.copy()
-            current_patch_params = patch_params.copy()
-
-        else:
-            current_vis_params = {}
-            current_filter_params = {}
-            current_seg_params = {}
-            current_patch_params = {}
-
-            for key in vis_params.keys():
-                if legacy_support and key == "vis_level":
-                    df.loc[idx, key] = -1
-                current_vis_params.update({key: df.loc[idx, key]})
-
-            for key in filter_params.keys():
-                if legacy_support and key == "a_t":
-                    old_area = df.loc[idx, "a"]
-                    seg_level = df.loc[idx, "seg_level"]
-                    scale = WSI_object.level_downsamples[seg_level]
-                    adjusted_area = int(old_area * (scale[0] * scale[1]) / (512 * 512))
-                    current_filter_params.update({key: adjusted_area})
-                    df.loc[idx, key] = adjusted_area
-                current_filter_params.update({key: df.loc[idx, key]})
-
-            for key in seg_params.keys():
-                if legacy_support and key == "seg_level":
-                    df.loc[idx, key] = -1
-                current_seg_params.update({key: df.loc[idx, key]})
-
-            for key in patch_params.keys():
-                current_patch_params.update({key: df.loc[idx, key]})
-
-        if current_vis_params["vis_level"] < 0:
-            if len(WSI_object.level_dim) == 1:
-                current_vis_params["vis_level"] = 0
-
-            else:
-                wsi = WSI_object.getOpenSlide()
-                best_level = wsi.get_best_level_for_downsample(64)
-                current_vis_params["vis_level"] = best_level
-
-        if current_seg_params["seg_level"] < 0:
-            if len(WSI_object.level_dim) == 1:
-                current_seg_params["seg_level"] = 0
-
-            else:
-                wsi = WSI_object.getOpenSlide()
-                best_level = wsi.get_best_level_for_downsample(64)
-                current_seg_params["seg_level"] = best_level
-
-        keep_ids = str(current_seg_params["keep_ids"])
-        if keep_ids != "none" and len(keep_ids) > 0:
-            str_ids = current_seg_params["keep_ids"]
-            current_seg_params["keep_ids"] = np.array(str_ids.split(",")).astype(int)
-        else:
-            current_seg_params["keep_ids"] = []
-
-        exclude_ids = str(current_seg_params["exclude_ids"])
-        if exclude_ids != "none" and len(exclude_ids) > 0:
-            str_ids = current_seg_params["exclude_ids"]
-            current_seg_params["exclude_ids"] = np.array(str_ids.split(",")).astype(int)
-        else:
-            current_seg_params["exclude_ids"] = []
-
-        w, h = WSI_object.level_dim[current_seg_params["seg_level"]]
-        if w * h > 1e8:
-            print(
-                "level_dim {} x {} is likely too large for successful segmentation,"
-                " aborting".format(w, h)
-            )
-            df.loc[idx, "status"] = "failed_seg"
-            continue
-
-        df.loc[idx, "vis_level"] = current_vis_params["vis_level"]
-        df.loc[idx, "seg_level"] = current_seg_params["seg_level"]
-
-        seg_time_elapsed = -1
-        if seg:
-            mask_file = None
-            if segmentation_dir is not None:
-                print("Attempting to find pre-made segmentation...")
-                mask_file = os.path.join(segmentation_dir, f"{slide_id}.pkl")
-                if os.path.exists(mask_file):
-                    print("Found it, will not segment tissue:", mask_file)
-                else:
-                    print("Not found, segmenting tissue now.")
-                    mask_file = None
-            else:
-                print("No segmentation dir passed... segmenting tissue.")
-            try:
-                WSI_object, seg_time_elapsed = segment(
-                    WSI_object,
-                    current_seg_params,
-                    current_filter_params,
-                    mask_file=mask_file,
-                )
-            except Exception as e:
-                print(f"Failed to segment slide, skipping {full_path}")
-                print("Error", e)
-                continue
-
-        if save_mask:
-            mask = WSI_object.visWSI(**current_vis_params)
-            mask_path = os.path.join(mask_save_dir, slide_id + ".jpg")
-            mask.save(mask_path)
-
-        patch_time_elapsed = -1  # Default time
-        if patch:
-            # -----------------------------------------------------------------------
-            # Added by Jakub Kaczmarzyk (github kaczmarj) to get patch size for a
-            # particular spacing. The patching happens at the highest resolution, but
-            # we want to extract patches at a particular spacing.
-            this_step_size = None
-            if patch_spacing is not None:
-                try:
-                    slide_mpp = get_avg_mpp(full_path)
-                except CannotReadSpacing:
-                    print("!" * 40)
-                    print("SKIPPING this slide because the spacing cannot be read")
-                    print("!" * 40)
-                    continue
-
-                patch_size = orig_patch_size * patch_spacing / slide_mpp
-                patch_size = round(patch_size)
-                print(
-                    "Scaled patch size by the patch spacing (result is patches of"
-                    f" {patch_size * slide_mpp} microns)"
-                )
-
-                # We use the variable orig_step_size because
-                if orig_step_size is not None:
-                    this_step_size = orig_step_size * patch_spacing / slide_mpp
-                    this_step_size = round(this_step_size)
-                    print(
-                        "Scaled step size by the patch spacing (result is steps of"
-                        f" {this_step_size * slide_mpp} microns)"
-                    )
-
-            step_size = this_step_size or patch_size
-            print(f"Using patch size = {patch_size} @ {slide_mpp} MPP")
-            print(f"Using step size = {step_size} @ {slide_mpp} MPP")
-            # ----------------------------------------------------------------------
-
-            current_patch_params.update(
-                {
-                    "patch_level": patch_level,
-                    "patch_size": patch_size,
-                    "step_size": step_size,
-                    "save_path": patch_save_dir,
-                }
-            )
-            try:
-                file_path, patch_time_elapsed = patching(
-                    WSI_object=WSI_object,
-                    **current_patch_params,
-                )
-            except Exception as e:
-                print(f"Failed to patch slide, skipping {full_path}")
-                print("Error", e)
-                continue
-
-        stitch_time_elapsed = -1
-        if stitch:
-            file_path = os.path.join(patch_save_dir, slide_id + ".h5")
-            if os.path.isfile(file_path):
-                heatmap, stitch_time_elapsed = stitching(
-                    file_path, WSI_object, downscale=64
-                )
-                stitch_path = os.path.join(stitch_save_dir, slide_id + ".jpg")
-                heatmap.save(stitch_path)
-
-        print("segmentation took {} seconds".format(seg_time_elapsed))
-        print("patching took {} seconds".format(patch_time_elapsed))
-        print("stitching took {} seconds".format(stitch_time_elapsed))
-        df.loc[idx, "status"] = "processed"
-
-        seg_times += seg_time_elapsed
-        patch_times += patch_time_elapsed
-        stitch_times += stitch_time_elapsed
-
-    if total != 0:
-        seg_times /= total
-        patch_times /= total
-        stitch_times /= total
-
-    df.to_csv(os.path.join(save_dir, "process_list_autogen.csv"), index=False)
-    print("average segmentation time in s per slide: {}".format(seg_times))
-    print("average patching time in s per slide: {}".format(patch_times))
-    print("average stiching time in s per slide: {}".format(stitch_times))
-
-    return seg_times, patch_times
-
-
-def create_patches(
-    source: str,
-    patch_size: int,
-    patch_spacing: float,
-    save_dir: str,
-    step_size: Optional[int] = None,
-    patch: bool = True,
-    seg: bool = True,
-    stitch: bool = True,
-    auto_skip: bool = True,
-    preset=None,
-    process_list=None,
-    segmentation_dir=None,
-):
-    patch_save_dir = os.path.join(save_dir, "patches")
-    mask_save_dir = os.path.join(save_dir, "masks")
-    stitch_save_dir = os.path.join(save_dir, "stitches")
-
-    if process_list:
-        process_list = os.path.join(save_dir, process_list)
-
-    else:
-        process_list = None
-
-    print("source: ", source)
-    print("mask read dir: ", segmentation_dir or "<not specified>")
-    print("patch_save_dir: ", patch_save_dir)
-    print("mask_save_dir: ", mask_save_dir)
-    print("stitch_save_dir: ", stitch_save_dir)
-
-    directories = {
-        "source": source,
-        "save_dir": save_dir,
-        "patch_save_dir": patch_save_dir,
-        "mask_save_dir": mask_save_dir,
-        "stitch_save_dir": stitch_save_dir,
-    }
-
-    for key, val in directories.items():
-        print("{} : {}".format(key, val))
-        if key not in ["source"]:
-            os.makedirs(val, exist_ok=True)
-
-    seg_params = {
-        "seg_level": -1,
-        "sthresh": 8,
-        "mthresh": 7,
-        "close": 4,
-        "use_otsu": False,
-        "keep_ids": "none",
-        "exclude_ids": "none",
-    }
-    filter_params = {"a_t": 100, "a_h": 16, "max_n_holes": 8}
-    vis_params = {"vis_level": -1, "line_thickness": 250}
-    patch_params = {"use_padding": True, "contour_fn": "four_pt"}
-
-    if preset:
-        preset_df = pd.read_csv(_script_path / "presets" / preset)
-        for key in seg_params.keys():
-            seg_params[key] = preset_df.loc[0, key]
-
-        for key in filter_params.keys():
-            filter_params[key] = preset_df.loc[0, key]  # type: ignore
-
-        for key in vis_params.keys():
-            vis_params[key] = preset_df.loc[0, key]  # type: ignore
-
-        for key in patch_params.keys():
-            patch_params[key] = preset_df.loc[0, key]
-
-    parameters = {
-        "seg_params": seg_params,
-        "filter_params": filter_params,
-        "patch_params": patch_params,
-        "vis_params": vis_params,
-    }
-
-    print(parameters)
-
-    seg_and_patch(
-        **directories,
-        **parameters,
-        patch_size=patch_size,
-        step_size=step_size,
-        seg=seg,
-        use_default_params=False,
-        save_mask=True,
-        stitch=stitch,
-        patch_level=0,  # args.patch_level,
-        patch=patch,
-        process_list=process_list,
-        auto_skip=auto_skip,
-        patch_spacing=patch_spacing,
-        segmentation_dir=segmentation_dir,
-    )
diff --git a/wsinfer/patchlib/patch.py b/wsinfer/patchlib/patch.py
new file mode 100644
index 0000000..27f4fec
--- /dev/null
+++ b/wsinfer/patchlib/patch.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import itertools
+import logging
+from typing import Sequence
+
+import cv2 as cv
+import numpy as np
+import numpy.typing as npt
+from shapely import MultiPolygon
+from shapely import Point
+from shapely import Polygon
+from shapely import STRtree
+
+logger = logging.getLogger(__name__)
+
+
+def get_multipolygon_from_binary_arr(
+    arr: npt.NDArray[np.int_], scale: tuple[float, float] | None = None
+) -> tuple[MultiPolygon, Sequence[npt.NDArray[np.int_]], npt.NDArray[np.int_]]:
+    """Create a Shapely Polygon from a binary array."""
+    # Find contours and hierarchy
+    contours: Sequence[npt.NDArray]
+    hierarchy: npt.NDArray[np.int_]
+    contours, hierarchy = cv.findContours(arr, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
+    hierarchy = hierarchy.squeeze(0)
+
+    logger.info(f"Detected {len(contours)} contours")
+    contours_unscaled = contours
+    if scale is not None:
+        logger.info(
+            "Scaling contours to slide-level (level=0) coordinate space by multiplying"
+            f" by {scale}"
+        )
+        # Reshape to broadcast with contour coordinates.
+        scale_arr: npt.NDArray[np.float_] = np.array(scale).reshape(1, 1, 2)
+        contours = tuple(c * scale_arr for c in contours_unscaled)
+        del scale_arr
+
+    # From https://stackoverflow.com/a/75510437/5666087
+    def merge_polygons(polygon: MultiPolygon, idx: int, add: bool) -> MultiPolygon:
+        """
+        polygon: Main polygon to which a new polygon is added
+        idx: Index of contour
+        add: If this contour should be added (True) or subtracted (False)
+        """
+
+        # Get contour from global list of contours
+        contour = np.squeeze(contours[idx])
+
+        # cv2.findContours() sometimes returns a single point -> skip this case
+        if len(contour) > 2:
+            # Convert contour to shapely polygon
+            new_poly = Polygon(contour)
+
+            # Not all polygons are shapely-valid (self intersection, etc.)
+            if not new_poly.is_valid:
+                # Convert invalid polygon to valid
+                new_poly = new_poly.buffer(0)
+
+            # Merge new polygon with the main one
+            if add:
+                polygon = polygon.union(new_poly)
+            else:
+                polygon = polygon.difference(new_poly)
+
+        # Check if current polygon has a child
+        child_idx = hierarchy[idx][2]
+        if child_idx >= 0:
+            # Call this function recursively, negate `add` parameter
+            polygon = merge_polygons(polygon, child_idx, not add)
+
+        # Check if there is some next polygon at the same hierarchy level
+        next_idx = hierarchy[idx][0]
+        if next_idx >= 0:
+            # Call this function recursively
+            polygon = merge_polygons(polygon, next_idx, add)
+
+        return polygon
+
+    # Call the function with an initial empty polygon and start from contour 0
+    polygon = merge_polygons(MultiPolygon(), 0, True)
+
+    # Add back the axis in hierarchy because we squeezed it before.
+    return polygon, contours_unscaled, hierarchy[np.newaxis]
+
+
+def get_nonoverlapping_patch_coordinates_within_polygon(
+    slide_width: int,
+    slide_height: int,
+    patch_size: int,
+    half_patch_size: int,
+    polygon: Polygon,
+) -> npt.NDArray[np.int_]:
+    """Get coordinates of patches within a polygon.
+
+    Returns
+    -------
+    Array with shape (N, 4), where N is the number of tiles. Each row in this array
+    contains the coordinates of a tile: (minx, miny, width, height).
+    """
+
+    # Make an array of Nx2, where each row is (x, y) centroid of the patch.
+    tile_centroids_arr: npt.NDArray[np.int_] = np.array(
+        list(
+            itertools.product(
+                range(0 + half_patch_size, slide_width, patch_size),
+                range(0 + half_patch_size, slide_height, patch_size),
+            )
+        )
+    )
+
+    tile_centroids_poly = [Point(c) for c in tile_centroids_arr]
+
+    # Query which centroids are inside the polygon.
+    tree = STRtree(tile_centroids_poly)
+    centroid_indexes_in_polygon = tree.query(polygon, predicate="contains")
+
+    # Sort so x and y are in ascending order (and y changes most rapidly).
+    centroid_indexes_in_polygon.sort()
+    tile_centroids_in_polygon = tile_centroids_arr[centroid_indexes_in_polygon]
+
+    # Transform the centroids to the upper-left point (x, y).
+    tile_minx_miny_in_polygon = tile_centroids_in_polygon - half_patch_size
+
+    # Add the patch size to the coordinate array.
+    # patch_size_arr = np.full_like(tile_minx_miny_in_polygon, patch_size)
+    # coords = np.concatenate((tile_minx_miny_in_polygon, patch_size_arr), axis=1)
+
+    return tile_minx_miny_in_polygon
diff --git a/wsinfer/patchlib/presets/tcga.csv b/wsinfer/patchlib/presets/tcga.csv
deleted file mode 100644
index 0005cd9..0000000
--- a/wsinfer/patchlib/presets/tcga.csv
+++ /dev/null
@@ -1,2 +0,0 @@
-seg_level,sthresh,mthresh,close,use_otsu,a_t,a_h,max_n_holes,vis_level,line_thickness,white_thresh,black_thresh,use_padding,contour_fn,keep_ids,exclude_ids
--1,8,7,4,FALSE,16,4,8,-1,100,5,50,TRUE,four_pt,none,none
diff --git a/wsinfer/patchlib/segment.py b/wsinfer/patchlib/segment.py
new file mode 100644
index 0000000..3adfead
--- /dev/null
+++ b/wsinfer/patchlib/segment.py
@@ -0,0 +1,69 @@
+"""Segment thumbnail of a whole slide image."""
+
+from __future__ import annotations
+
+import cv2 as cv
+import numpy as np
+import numpy.typing as npt
+from skimage.morphology import binary_closing
+from skimage.morphology import remove_small_holes
+from skimage.morphology import remove_small_objects
+
+
+def segment_tissue(
+    im_arr: npt.NDArray[np.uint8],
+    median_filter_size: int = 7,
+    binary_threshold: int = 7,
+    closing_kernel_size: int = 6,
+    min_object_size_px: int = 512,
+    min_hole_size_px: int = 1024,
+) -> npt.NDArray[np.bool_]:
+    """Create a binary tissue mask from an image.
+
+    Parameters
+    ----------
+    im_arr : array-like
+        RGB image array (uint8).
+    """
+    im_arr = np.asarray(im_arr)
+    assert im_arr.ndim == 3
+    assert im_arr.shape[2] == 3
+
+    # Convert to HSV color space.
+    im_arr = cv.cvtColor(im_arr, cv.COLOR_RGB2HSV)
+    im_arr = im_arr[:, :, 1]  # Keep saturation channel only.
+
+    # Use median blurring to smooth the image.
+    if median_filter_size <= 1 or median_filter_size % 2 == 0:
+        raise ValueError(
+            "median_filter_size must be greater than 1 and odd, but got"
+            f" {median_filter_size}"
+        )
+
+    # We use opencv here instead of PIL because opencv is _much_ faster. We use skimage
+    # further down for artifact removal (hole filling, object removal) because skimage
+    # provides easy to use methods for those.
+    im_arr = cv.medianBlur(im_arr, median_filter_size)
+
+    # Binarize image.
+    _, im_arr = cv.threshold(
+        im_arr, thresh=binary_threshold, maxval=255, type=cv.THRESH_BINARY
+    )
+
+    # Convert to boolean dtype. This helps with static type analysis because at this
+    # point, im_arr is a uint8 array.
+    im_arr_binary = im_arr > 0
+
+    # Closing. This removes small holes. It might not be entirely necessary because
+    # we have hole removal below.
+    im_arr_binary = binary_closing(
+        im_arr_binary, footprint=np.ones((closing_kernel_size, closing_kernel_size))
+    )
+
+    # Remove small objects.
+    im_arr_binary = remove_small_objects(im_arr_binary, min_size=min_object_size_px)
+
+    # Remove small holes.
+    im_arr_binary = remove_small_holes(im_arr_binary, area_threshold=min_hole_size_px)
+
+    return im_arr_binary
diff --git a/wsinfer/patchlib/utils/__init__.py b/wsinfer/patchlib/utils/__init__.py
deleted file mode 100644
index 9d48db4..0000000
--- a/wsinfer/patchlib/utils/__init__.py
+++ /dev/null
@@ -1,1 +0,0 @@
-from __future__ import annotations
diff --git a/wsinfer/patchlib/utils/file_utils.py b/wsinfer/patchlib/utils/file_utils.py
deleted file mode 100644
index 4f2ef8d..0000000
--- a/wsinfer/patchlib/utils/file_utils.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from __future__ import annotations
-
-import pickle
-
-import h5py
-
-
-def save_pkl(filename, save_object):
-    writer = open(filename, "wb")
-    pickle.dump(save_object, writer)
-    writer.close()
-
-
-def load_pkl(filename):
-    loader = open(filename, "rb")
-    file = pickle.load(loader)
-    loader.close()
-    return file
-
-
-def save_hdf5(output_path, asset_dict, attr_dict=None, mode="a"):
-    file = h5py.File(output_path, mode)
-    for key, val in asset_dict.items():
-        data_shape = val.shape
-        if key not in file:
-            data_type = val.dtype
-            chunk_shape = (1,) + data_shape[1:]
-            maxshape = (None,) + data_shape[1:]
-            dset = file.create_dataset(
-                key,
-                shape=data_shape,
-                maxshape=maxshape,
-                chunks=chunk_shape,
-                dtype=data_type,
-            )
-            dset[:] = val
-            if attr_dict is not None:
-                if key in attr_dict.keys():
-                    for attr_key, attr_val in attr_dict[key].items():
-                        dset.attrs[attr_key] = attr_val
-        else:
-            dset = file[key]
-            dset.resize(len(dset) + data_shape[0], axis=0)
-            dset[-data_shape[0] :] = val
-    file.close()
-    return output_path
diff --git a/wsinfer/patchlib/wsi_core/WholeSlideImage.py b/wsinfer/patchlib/wsi_core/WholeSlideImage.py
deleted file mode 100644
index c7703e6..0000000
--- a/wsinfer/patchlib/wsi_core/WholeSlideImage.py
+++ /dev/null
@@ -1,818 +0,0 @@
-from __future__ import annotations
-
-import math
-import multiprocessing as mp
-import os
-from xml.dom import minidom
-
-import cv2
-import numpy as np
-from PIL import Image
-
-from wsinfer.wsi import WSI
-
-from ..utils.file_utils import load_pkl
-from ..utils.file_utils import save_pkl
-from .util_classes import Contour_Checking_fn
-from .util_classes import isInContourV1
-from .util_classes import isInContourV2
-from .util_classes import isInContourV3_Easy
-from .util_classes import isInContourV3_Hard
-from .wsi_utils import initialize_hdf5_bag
-from .wsi_utils import isBlackPatch
-from .wsi_utils import isWhitePatch
-from .wsi_utils import save_hdf5
-from .wsi_utils import savePatchIter_bag_hdf5
-
-Image.MAX_IMAGE_PIXELS = 933120000
-
-
-class WholeSlideImage(object):
-    def __init__(self, path):
-        """
-        Args:
-            path (str): fullpath to WSI file
-        """
-
-        #         self.name = ".".join(path.split("/")[-1].split('.')[:-1])
-        self.name = os.path.splitext(os.path.basename(path))[0]
-        self.wsi = WSI(path)
-        self.level_downsamples = self._assertLevelDownsamples()
-        self.level_dim = self.wsi.level_dimensions
-
-        self.contours_tissue = None
-        self.contours_tumor = None
-        self.hdf5_file = None
-
-    def getOpenSlide(self):
-        return self.wsi
-
-    def initXML(self, xml_path):
-        def _createContour(coord_list):
-            return np.array(
-                [
-                    [
-                        [
-                            int(float(coord.attributes["X"].value)),
-                            int(float(coord.attributes["Y"].value)),
-                        ]
-                    ]
-                    for coord in coord_list
-                ],
-                dtype="int32",
-            )
-
-        xmldoc = minidom.parse(xml_path)
-        annotations = [
-            anno.getElementsByTagName("Coordinate")
-            for anno in xmldoc.getElementsByTagName("Annotation")
-        ]
-        self.contours_tumor = [_createContour(coord_list) for coord_list in annotations]
-        self.contours_tumor = sorted(
-            self.contours_tumor, key=cv2.contourArea, reverse=True
-        )
-
-    def initTxt(self, annot_path):
-        def _create_contours_from_dict(annot):
-            all_cnts = []
-            for idx, annot_group in enumerate(annot):
-                contour_group = annot_group["coordinates"]
-                if annot_group["type"] == "Polygon":
-                    for idx, contour in enumerate(contour_group):
-                        contour = np.array(contour).astype(np.int32).reshape(-1, 1, 2)
-                        all_cnts.append(contour)
-
-                else:
-                    for idx, sgmt_group in enumerate(contour_group):
-                        contour = []
-                        for sgmt in sgmt_group:
-                            contour.extend(sgmt)
-                        contour = np.array(contour).astype(np.int32).reshape(-1, 1, 2)
-                        all_cnts.append(contour)
-
-            return all_cnts
-
-        with open(annot_path, "r") as f:
-            annot = f.read()
-            annot = eval(annot)
-        self.contours_tumor = _create_contours_from_dict(annot)
-        self.contours_tumor = sorted(
-            self.contours_tumor, key=cv2.contourArea, reverse=True
-        )
-
-    def initSegmentation(self, mask_file):
-        # load segmentation results from pickle file
-        asset_dict = load_pkl(mask_file)
-        self.holes_tissue = asset_dict["holes"]
-        self.contours_tissue = asset_dict["tissue"]
-
-    def saveSegmentation(self, mask_file):
-        # save segmentation results using pickle
-        asset_dict = {"holes": self.holes_tissue, "tissue": self.contours_tissue}
-        save_pkl(mask_file, asset_dict)
-
-    def segmentTissue(
-        self,
-        seg_level=0,
-        sthresh=20,
-        sthresh_up=255,
-        mthresh=7,
-        close=0,
-        use_otsu=False,
-        filter_params={"a_t": 100},
-        ref_patch_size=512,
-        exclude_ids=[],
-        keep_ids=[],
-    ):
-        """
-        Segment the tissue via HSV -> Median thresholding -> Binary threshold
-        """
-
-        def _filter_contours(contours, hierarchy, filter_params):
-            """
-            Filter contours by: area.
-            """
-            filtered = []
-
-            # find indices of foreground contours (parent == -1)
-            hierarchy_1 = np.flatnonzero(hierarchy[:, 1] == -1)
-            all_holes = []
-
-            # loop through foreground contour indices
-            for cont_idx in hierarchy_1:
-                # actual contour
-                cont = contours[cont_idx]
-                # indices of holes contained in this contour
-                # (children of parent contour)
-                holes = np.flatnonzero(hierarchy[:, 1] == cont_idx)
-                # take contour area (includes holes)
-                a = cv2.contourArea(cont)
-                # calculate the contour area of each hole
-                hole_areas = [cv2.contourArea(contours[hole_idx]) for hole_idx in holes]
-                # actual area of foreground contour region
-                a = a - np.array(hole_areas).sum()
-                if a == 0:
-                    continue
-                if tuple((filter_params["a_t"],)) < tuple((a,)):
-                    filtered.append(cont_idx)
-                    all_holes.append(holes)
-
-            foreground_contours = [contours[cont_idx] for cont_idx in filtered]
-
-            hole_contours = []
-
-            for hole_ids in all_holes:
-                unfiltered_holes = [contours[idx] for idx in hole_ids]
-                unfilered_holes = sorted(
-                    unfiltered_holes, key=cv2.contourArea, reverse=True
-                )
-                # take max_n_holes largest holes by area
-                unfilered_holes = unfilered_holes[: filter_params["max_n_holes"]]
-                filtered_holes = []
-
-                # filter these holes
-                for hole in unfilered_holes:
-                    if cv2.contourArea(hole) > filter_params["a_h"]:
-                        filtered_holes.append(hole)
-
-                hole_contours.append(filtered_holes)
-
-            return foreground_contours, hole_contours
-
-        img = np.array(
-            self.wsi.read_region((0, 0), seg_level, self.level_dim[seg_level])
-        )
-        img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)  # Convert to HSV space
-        img_med = cv2.medianBlur(img_hsv[:, :, 1], mthresh)  # Apply median blurring
-
-        # Thresholding
-        if use_otsu:
-            _, img_otsu = cv2.threshold(
-                img_med, 0, sthresh_up, cv2.THRESH_OTSU + cv2.THRESH_BINARY
-            )
-        else:
-            _, img_otsu = cv2.threshold(img_med, sthresh, sthresh_up, cv2.THRESH_BINARY)
-
-        # Morphological closing
-        if close > 0:
-            kernel = np.ones((close, close), np.uint8)
-            img_otsu = cv2.morphologyEx(img_otsu, cv2.MORPH_CLOSE, kernel)
-
-        scale = self.level_downsamples[seg_level]
-        scaled_ref_patch_area = int(ref_patch_size**2 / (scale[0] * scale[1]))
-        filter_params = filter_params.copy()
-        filter_params["a_t"] = filter_params["a_t"] * scaled_ref_patch_area
-        filter_params["a_h"] = filter_params["a_h"] * scaled_ref_patch_area
-
-        # Find and filter contours
-        contours, hierarchy = cv2.findContours(
-            img_otsu, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE
-        )  # Find contours
-        hierarchy = np.squeeze(hierarchy, axis=(0,))[:, 2:]
-        if filter_params:
-            foreground_contours, hole_contours = _filter_contours(
-                contours, hierarchy, filter_params
-            )  # Necessary for filtering out artifacts
-
-        self.contours_tissue = self.scaleContourDim(foreground_contours, scale)
-        self.holes_tissue = self.scaleHolesDim(hole_contours, scale)
-
-        # exclude_ids = [0,7,9]
-        if len(keep_ids) > 0:
-            contour_ids = set(keep_ids) - set(exclude_ids)
-        else:
-            contour_ids = set(np.arange(len(self.contours_tissue))) - set(exclude_ids)
-
-        self.contours_tissue = [self.contours_tissue[i] for i in contour_ids]
-        self.holes_tissue = [self.holes_tissue[i] for i in contour_ids]
-
-    def visWSI(
-        self,
-        vis_level=0,
-        color=(0, 255, 0),
-        hole_color=(0, 0, 255),
-        annot_color=(255, 0, 0),
-        line_thickness=250,
-        max_size=None,
-        top_left=None,
-        bot_right=None,
-        custom_downsample=1,
-        view_slide_only=False,
-        number_contours=False,
-        seg_display=True,
-        annot_display=True,
-    ):
-        downsample = self.level_downsamples[vis_level]
-        scale = [1 / downsample[0], 1 / downsample[1]]
-
-        if top_left is not None and bot_right is not None:
-            top_left = tuple(top_left)
-            bot_right = tuple(bot_right)
-            w, h = tuple(
-                (np.array(bot_right) * scale).astype(int)
-                - (np.array(top_left) * scale).astype(int)
-            )
-            region_size = (w, h)
-        else:
-            top_left = (0, 0)
-            region_size = self.level_dim[vis_level]
-
-        img = np.array(
-            self.wsi.read_region(top_left, vis_level, region_size).convert("RGB")
-        )
-
-        if not view_slide_only:
-            offset = tuple(-(np.array(top_left) * scale).astype(int))
-            line_thickness = int(line_thickness * math.sqrt(scale[0] * scale[1]))
-            if self.contours_tissue is not None and seg_display:
-                if not number_contours:
-                    cv2.drawContours(
-                        img,
-                        self.scaleContourDim(self.contours_tissue, scale),
-                        -1,
-                        color,
-                        line_thickness,
-                        lineType=cv2.LINE_8,
-                        offset=offset,
-                    )
-
-                else:  # add numbering to each contour
-                    for idx, cont in enumerate(self.contours_tissue):
-                        contour = np.array(self.scaleContourDim(cont, scale))
-                        M = cv2.moments(contour)
-                        cX = int(M["m10"] / (M["m00"] + 1e-9))
-                        cY = int(M["m01"] / (M["m00"] + 1e-9))
-                        # draw the contour and put text next to center
-                        cv2.drawContours(
-                            img,
-                            [contour],
-                            -1,
-                            color,
-                            line_thickness,
-                            lineType=cv2.LINE_8,
-                            offset=offset,
-                        )
-                        cv2.putText(
-                            img,
-                            "{}".format(idx),
-                            (cX, cY),
-                            cv2.FONT_HERSHEY_SIMPLEX,
-                            2,
-                            (255, 0, 0),
-                            10,
-                        )
-
-                for holes in self.holes_tissue:
-                    cv2.drawContours(
-                        img,
-                        self.scaleContourDim(holes, scale),
-                        -1,
-                        hole_color,
-                        line_thickness,
-                        lineType=cv2.LINE_8,
-                    )
-
-            if self.contours_tumor is not None and annot_display:
-                cv2.drawContours(
-                    img,
-                    self.scaleContourDim(self.contours_tumor, scale),
-                    -1,
-                    annot_color,
-                    line_thickness,
-                    lineType=cv2.LINE_8,
-                    offset=offset,
-                )
-
-        img = Image.fromarray(img)
-
-        w, h = img.size
-        if custom_downsample > 1:
-            img = img.resize((int(w / custom_downsample), int(h / custom_downsample)))
-
-        if max_size is not None and (w > max_size or h > max_size):
-            resizeFactor = max_size / w if w > h else max_size / h
-            img = img.resize((int(w * resizeFactor), int(h * resizeFactor)))
-
-        return img
-
-    def createPatches_bag_hdf5(
-        self,
-        save_path,
-        patch_level=0,
-        patch_size=256,
-        step_size=256,
-        save_coord=True,
-        **kwargs,
-    ):
-        contours = self.contours_tissue
-
-        print(
-            "Creating patches for: ",
-            self.name,
-            "...",
-        )
-        for idx, cont in enumerate(contours):
-            patch_gen = self._getPatchGenerator(
-                cont, idx, patch_level, save_path, patch_size, step_size, **kwargs
-            )
-
-            if self.hdf5_file is None:
-                try:
-                    first_patch = next(patch_gen)
-
-                # empty contour, continue
-                except StopIteration:
-                    continue
-
-                file_path = initialize_hdf5_bag(first_patch, save_coord=save_coord)
-                self.hdf5_file = file_path
-
-            for patch in patch_gen:
-                savePatchIter_bag_hdf5(patch)
-
-        return self.hdf5_file
-
-    def _getPatchGenerator(
-        self,
-        cont,
-        cont_idx,
-        patch_level,
-        save_path,
-        patch_size=256,
-        step_size=256,
-        custom_downsample=1,
-        white_black=True,
-        white_thresh=15,
-        black_thresh=50,
-        contour_fn="four_pt",
-        use_padding=True,
-    ):
-        start_x, start_y, w, h = (
-            cv2.boundingRect(cont)
-            if cont is not None
-            else (0, 0, self.level_dim[patch_level][0], self.level_dim[patch_level][1])
-        )
-        print("Bounding Box:", start_x, start_y, w, h)
-        print("Contour Area:", cv2.contourArea(cont))
-
-        if custom_downsample > 1:
-            assert custom_downsample == 2
-            target_patch_size = patch_size
-            patch_size = target_patch_size * 2
-            step_size = step_size * 2
-            print(
-                "Custom Downsample: {}, Patching at {} x {}, But Final Patch Size is"
-                " {} x {}".format(
-                    custom_downsample,
-                    patch_size,
-                    patch_size,
-                    target_patch_size,
-                    target_patch_size,
-                )
-            )
-
-        patch_downsample = (
-            int(self.level_downsamples[patch_level][0]),
-            int(self.level_downsamples[patch_level][1]),
-        )
-        ref_patch_size = (
-            patch_size * patch_downsample[0],
-            patch_size * patch_downsample[1],
-        )
-
-        step_size_x = step_size * patch_downsample[0]
-        step_size_y = step_size * patch_downsample[1]
-
-        if isinstance(contour_fn, str):
-            if contour_fn == "four_pt":
-                cont_check_fn = isInContourV3_Easy(
-                    contour=cont, patch_size=ref_patch_size[0], center_shift=0.5
-                )
-            elif contour_fn == "four_pt_hard":
-                cont_check_fn = isInContourV3_Hard(
-                    contour=cont, patch_size=ref_patch_size[0], center_shift=0.5
-                )
-            elif contour_fn == "center":
-                cont_check_fn = isInContourV2(
-                    contour=cont, patch_size=ref_patch_size[0]
-                )
-            elif contour_fn == "basic":
-                cont_check_fn = isInContourV1(contour=cont)
-            else:
-                raise NotImplementedError
-        else:
-            assert isinstance(contour_fn, Contour_Checking_fn)
-            cont_check_fn = contour_fn
-
-        img_w, img_h = self.level_dim[0]
-        if use_padding:
-            stop_y = start_y + h
-            stop_x = start_x + w
-        else:
-            stop_y = min(start_y + h, img_h - ref_patch_size[1])
-            stop_x = min(start_x + w, img_w - ref_patch_size[0])
-
-        count = 0
-        for y in range(start_y, stop_y, step_size_y):
-            for x in range(start_x, stop_x, step_size_x):
-                if not self.isInContours(
-                    cont_check_fn,
-                    (x, y),
-                    self.holes_tissue[cont_idx],
-                    ref_patch_size[0],
-                ):  # point not inside contour and its associated holes
-                    continue
-
-                count += 1
-                patch_PIL = self.wsi.read_region(
-                    (x, y), patch_level, (patch_size, patch_size)
-                ).convert("RGB")
-                if custom_downsample > 1:
-                    patch_PIL = patch_PIL.resize((target_patch_size, target_patch_size))
-
-                if white_black:
-                    if isBlackPatch(
-                        np.array(patch_PIL), rgbThresh=black_thresh
-                    ) or isWhitePatch(np.array(patch_PIL), satThresh=white_thresh):
-                        continue
-
-                patch_info = {
-                    "x": x // (patch_downsample[0] * custom_downsample),
-                    "y": y // (patch_downsample[1] * custom_downsample),
-                    "cont_idx": cont_idx,
-                    "patch_level": patch_level,
-                    "downsample": self.level_downsamples[patch_level],
-                    "downsampled_level_dim": tuple(
-                        np.array(self.level_dim[patch_level]) // custom_downsample
-                    ),
-                    "level_dim": self.level_dim[patch_level],
-                    "patch_PIL": patch_PIL,
-                    "name": self.name,
-                    "save_path": save_path,
-                }
-
-                yield patch_info
-
-        print("patches extracted: {}".format(count))
-
-    @staticmethod
-    def isInHoles(holes, pt, patch_size):
-        for hole in holes:
-            if (
-                cv2.pointPolygonTest(
-                    hole, (pt[0] + patch_size / 2, pt[1] + patch_size / 2), False
-                )
-                > 0
-            ):
-                return 1
-
-        return 0
-
-    @staticmethod
-    def isInContours(cont_check_fn, pt, holes=None, patch_size=256):
-        if cont_check_fn(pt):
-            if holes is not None:
-                return not WholeSlideImage.isInHoles(holes, pt, patch_size)
-            else:
-                return 1
-        return 0
-
-    @staticmethod
-    def scaleContourDim(contours, scale):
-        return [np.array(cont * scale, dtype="int32") for cont in contours]
-
-    @staticmethod
-    def scaleHolesDim(contours, scale):
-        return [
-            [np.array(hole * scale, dtype="int32") for hole in holes]
-            for holes in contours
-        ]
-
-    def _assertLevelDownsamples(self):
-        level_downsamples = []
-        dim_0 = self.wsi.level_dimensions[0]
-
-        for downsample, dim in zip(
-            self.wsi.level_downsamples, self.wsi.level_dimensions
-        ):
-            estimated_downsample = (dim_0[0] / float(dim[0]), dim_0[1] / float(dim[1]))
-            level_downsamples.append(estimated_downsample) if estimated_downsample != (
-                downsample,
-                downsample,
-            ) else level_downsamples.append((downsample, downsample))
-
-        return level_downsamples
-
-    def process_contours(
-        self, save_path, patch_level=0, patch_size=256, step_size=256, **kwargs
-    ):
-        save_path_hdf5 = os.path.join(save_path, str(self.name) + ".h5")
-        print(
-            "Creating patches for: ",
-            self.name,
-            "...",
-        )
-        n_contours = len(self.contours_tissue)
-        print("Total number of contours to process: ", n_contours)
-        fp_chunk_size = math.ceil(n_contours * 0.05)
-        init = True
-        for idx, cont in enumerate(self.contours_tissue):
-            if (idx + 1) % fp_chunk_size == fp_chunk_size:
-                print("Processing contour {}/{}".format(idx, n_contours))
-
-            asset_dict, attr_dict = self.process_contour(
-                cont,
-                self.holes_tissue[idx],
-                patch_level,
-                save_path,
-                patch_size,
-                step_size,
-                **kwargs,
-            )
-            if len(asset_dict) > 0:
-                if init:
-                    save_hdf5(save_path_hdf5, asset_dict, attr_dict, mode="w")
-                    init = False
-                else:
-                    save_hdf5(save_path_hdf5, asset_dict, mode="a")
-
-        return self.hdf5_file
-
-    def process_contour(
-        self,
-        cont,
-        contour_holes,
-        patch_level,
-        save_path,
-        patch_size=256,
-        step_size=256,
-        contour_fn="four_pt",
-        use_padding=True,
-        top_left=None,
-        bot_right=None,
-    ):
-        start_x, start_y, w, h = (
-            cv2.boundingRect(cont)
-            if cont is not None
-            else (0, 0, self.level_dim[patch_level][0], self.level_dim[patch_level][1])
-        )
-
-        patch_downsample = (
-            int(self.level_downsamples[patch_level][0]),
-            int(self.level_downsamples[patch_level][1]),
-        )
-        ref_patch_size = (
-            patch_size * patch_downsample[0],
-            patch_size * patch_downsample[1],
-        )
-
-        img_w, img_h = self.level_dim[0]
-        if use_padding:
-            stop_y = start_y + h
-            stop_x = start_x + w
-        else:
-            stop_y = min(start_y + h, img_h - ref_patch_size[1] + 1)
-            stop_x = min(start_x + w, img_w - ref_patch_size[0] + 1)
-
-        print("Bounding Box:", start_x, start_y, w, h)
-        print("Contour Area:", cv2.contourArea(cont))
-
-        if bot_right is not None:
-            stop_y = min(bot_right[1], stop_y)
-            stop_x = min(bot_right[0], stop_x)
-        if top_left is not None:
-            start_y = max(top_left[1], start_y)
-            start_x = max(top_left[0], start_x)
-
-        if bot_right is not None or top_left is not None:
-            w, h = stop_x - start_x, stop_y - start_y
-            if w <= 0 or h <= 0:
-                print("Contour is not in specified ROI, skip")
-                return {}, {}
-            else:
-                print("Adjusted Bounding Box:", start_x, start_y, w, h)
-
-        if isinstance(contour_fn, str):
-            if contour_fn == "four_pt":
-                cont_check_fn = isInContourV3_Easy(
-                    contour=cont, patch_size=ref_patch_size[0], center_shift=0.5
-                )
-            elif contour_fn == "four_pt_hard":
-                cont_check_fn = isInContourV3_Hard(
-                    contour=cont, patch_size=ref_patch_size[0], center_shift=0.5
-                )
-            elif contour_fn == "center":
-                cont_check_fn = isInContourV2(
-                    contour=cont, patch_size=ref_patch_size[0]
-                )
-            elif contour_fn == "basic":
-                cont_check_fn = isInContourV1(contour=cont)
-            else:
-                raise NotImplementedError
-        else:
-            assert isinstance(contour_fn, Contour_Checking_fn)
-            cont_check_fn = contour_fn
-
-        step_size_x = step_size * patch_downsample[0]
-        step_size_y = step_size * patch_downsample[1]
-
-        x_range = np.arange(start_x, stop_x, step=step_size_x)
-        y_range = np.arange(start_y, stop_y, step=step_size_y)
-        x_coords, y_coords = np.meshgrid(x_range, y_range, indexing="ij")
-        coord_candidates = np.array(
-            [x_coords.flatten(), y_coords.flatten()]
-        ).transpose()
-
-        num_workers = mp.cpu_count()
-        if num_workers > 4:
-            num_workers = 4
-        pool = mp.Pool(num_workers)
-
-        iterable = [
-            (coord, contour_holes, ref_patch_size[0], cont_check_fn)
-            for coord in coord_candidates
-        ]
-        results = pool.starmap(WholeSlideImage.process_coord_candidate, iterable)
-        pool.close()
-        results = np.array([result for result in results if result is not None])
-
-        print("Extracted {} coordinates".format(len(results)))
-
-        if len(results) > 1:
-            asset_dict = {"coords": results}
-
-            attr = {
-                "patch_size": patch_size,  # To be considered...
-                "patch_level": patch_level,
-                "downsample": self.level_downsamples[patch_level],
-                "downsampled_level_dim": tuple(np.array(self.level_dim[patch_level])),
-                "level_dim": self.level_dim[patch_level],
-                "name": self.name,
-                "save_path": save_path,
-            }
-
-            attr_dict = {"coords": attr}
-            return asset_dict, attr_dict
-
-        else:
-            return {}, {}
-
-    @staticmethod
-    def process_coord_candidate(coord, contour_holes, ref_patch_size, cont_check_fn):
-        if WholeSlideImage.isInContours(
-            cont_check_fn, coord, contour_holes, ref_patch_size
-        ):
-            return coord
-        else:
-            return None
-
-    def block_blending(
-        self,
-        img,
-        vis_level,
-        top_left,
-        bot_right,
-        alpha=0.5,
-        blank_canvas=False,
-        block_size=1024,
-    ):
-        print("\ncomputing blend")
-        downsample = self.level_downsamples[vis_level]
-        w = img.shape[1]
-        h = img.shape[0]
-        block_size_x = min(block_size, w)
-        block_size_y = min(block_size, h)
-        print("using block size: {} x {}".format(block_size_x, block_size_y))
-
-        shift = top_left  # amount shifted w.r.t. (0,0)
-        for x_start in range(
-            top_left[0], bot_right[0], block_size_x * int(downsample[0])
-        ):
-            for y_start in range(
-                top_left[1], bot_right[1], block_size_y * int(downsample[1])
-            ):
-                # print(x_start, y_start)
-
-                # 1. convert wsi coordinates to image coordinates via shift and scale
-                x_start_img = int((x_start - shift[0]) / int(downsample[0]))
-                y_start_img = int((y_start - shift[1]) / int(downsample[1]))
-
-                # 2. compute end points of blend tile, careful not to go over the edge
-                # of the image
-                y_end_img = min(h, y_start_img + block_size_y)
-                x_end_img = min(w, x_start_img + block_size_x)
-
-                if y_end_img == y_start_img or x_end_img == x_start_img:
-                    continue
-                # print('start_coord: {} end_coord: {}'.format(
-                # (x_start_img, y_start_img), (x_end_img, y_end_img)))
-
-                # 3. fetch blend block and size
-                blend_block = img[y_start_img:y_end_img, x_start_img:x_end_img]
-                blend_block_size = (x_end_img - x_start_img, y_end_img - y_start_img)
-
-                if not blank_canvas:
-                    # 4. read actual wsi block as canvas block
-                    pt = (x_start, y_start)
-                    canvas = np.array(
-                        self.wsi.read_region(pt, vis_level, blend_block_size).convert(
-                            "RGB"
-                        )
-                    )
-                else:
-                    # 4. OR create blank canvas block
-                    canvas = np.array(
-                        Image.new(
-                            size=blend_block_size, mode="RGB", color=(255, 255, 255)
-                        )
-                    )
-
-                # 5. blend color block and canvas block
-                img[y_start_img:y_end_img, x_start_img:x_end_img] = cv2.addWeighted(
-                    blend_block, alpha, canvas, 1 - alpha, 0, canvas
-                )
-        return img
-
-    def get_seg_mask(self, region_size, scale, use_holes=False, offset=(0, 0)):
-        print("\ncomputing foreground tissue mask")
-        tissue_mask = np.full(np.flip(region_size), 0).astype(np.uint8)
-        contours_tissue = self.scaleContourDim(self.contours_tissue, scale)
-        offset = tuple((np.array(offset) * np.array(scale) * -1).astype(np.int32))
-
-        contours_holes = self.scaleHolesDim(self.holes_tissue, scale)
-        contours_tissue, contours_holes = zip(
-            *sorted(
-                zip(contours_tissue, contours_holes),
-                key=lambda x: cv2.contourArea(x[0]),
-                reverse=True,
-            )
-        )
-        for idx in range(len(contours_tissue)):
-            cv2.drawContours(
-                image=tissue_mask,
-                contours=contours_tissue,
-                contourIdx=idx,
-                color=(1),
-                offset=offset,
-                thickness=-1,
-            )
-
-            if use_holes:
-                cv2.drawContours(
-                    image=tissue_mask,
-                    contours=contours_holes[idx],
-                    contourIdx=-1,
-                    color=(0),
-                    offset=offset,
-                    thickness=-1,
-                )
-            # contours_holes = self._scaleContourDim(self.holes_tissue, scale,
-            # holes=True, area_thresh=area_thresh)
-
-        tissue_mask = tissue_mask.astype(bool)
-        print(
-            "detected {}/{} of region as tissue".format(
-                tissue_mask.sum(), tissue_mask.size
-            )
-        )
-        return tissue_mask
diff --git a/wsinfer/patchlib/wsi_core/__init__.py b/wsinfer/patchlib/wsi_core/__init__.py
deleted file mode 100644
index 9d48db4..0000000
--- a/wsinfer/patchlib/wsi_core/__init__.py
+++ /dev/null
@@ -1,1 +0,0 @@
-from __future__ import annotations
diff --git a/wsinfer/patchlib/wsi_core/batch_process_utils.py b/wsinfer/patchlib/wsi_core/batch_process_utils.py
deleted file mode 100644
index 8358261..0000000
--- a/wsinfer/patchlib/wsi_core/batch_process_utils.py
+++ /dev/null
@@ -1,112 +0,0 @@
-from __future__ import annotations
-
-import numpy as np
-import pandas as pd
-
-
-def initialize_df(
-    slides,
-    seg_params,
-    filter_params,
-    vis_params,
-    patch_params,
-    use_heatmap_args=False,
-    save_patches=False,
-):
-    """
-    initiate a pandas df describing a list of slides to process
-    args:
-        slides (df or array-like):
-            array-like structure containing list of slide ids, if df, these ids assumed
-            to be stored under the 'slide_id' column
-        seg_params (dict): segmentation paramters
-        filter_params (dict): filter parameters
-        vis_params (dict): visualization paramters
-        patch_params (dict): patching paramters
-        use_heatmap_args (bool): whether to include heatmap arguments such as ROI
-            coordinates
-    """
-    total = len(slides)
-    if isinstance(slides, pd.DataFrame):
-        slide_ids = slides.slide_id.values
-    else:
-        slide_ids = slides
-    default_df_dict = {
-        "slide_id": slide_ids,
-        "process": np.full((total), 1, dtype=np.uint8),
-    }
-
-    # initiate empty labels in case not provided
-    if use_heatmap_args:
-        default_df_dict.update({"label": np.full((total), -1)})
-
-    default_df_dict.update(
-        {
-            "status": np.full((total), "tbp"),
-            # seg params
-            "seg_level": np.full((total), int(seg_params["seg_level"]), dtype=np.int8),
-            "sthresh": np.full((total), int(seg_params["sthresh"]), dtype=np.uint8),
-            "mthresh": np.full((total), int(seg_params["mthresh"]), dtype=np.uint8),
-            "close": np.full((total), int(seg_params["close"]), dtype=np.uint32),
-            "use_otsu": np.full((total), bool(seg_params["use_otsu"]), dtype=bool),
-            "keep_ids": np.full((total), seg_params["keep_ids"]),
-            "exclude_ids": np.full((total), seg_params["exclude_ids"]),
-            # filter params
-            "a_t": np.full((total), int(filter_params["a_t"]), dtype=np.float32),
-            "a_h": np.full((total), int(filter_params["a_h"]), dtype=np.float32),
-            "max_n_holes": np.full(
-                (total), int(filter_params["max_n_holes"]), dtype=np.uint32
-            ),
-            # vis params
-            "vis_level": np.full((total), int(vis_params["vis_level"]), dtype=np.int8),
-            "line_thickness": np.full(
-                (total), int(vis_params["line_thickness"]), dtype=np.uint32
-            ),
-            # patching params
-            "use_padding": np.full(
-                (total), bool(patch_params["use_padding"]), dtype=bool
-            ),
-            "contour_fn": np.full((total), patch_params["contour_fn"]),
-        }
-    )
-
-    if save_patches:
-        default_df_dict.update(
-            {
-                "white_thresh": np.full(
-                    (total), int(patch_params["white_thresh"]), dtype=np.uint8
-                ),
-                "black_thresh": np.full(
-                    (total), int(patch_params["black_thresh"]), dtype=np.uint8
-                ),
-            }
-        )
-
-    if use_heatmap_args:
-        # initiate empty x,y coordinates in case not provided
-        default_df_dict.update(
-            {
-                "x1": np.empty((total)).fill(np.NaN),
-                "x2": np.empty((total)).fill(np.NaN),
-                "y1": np.empty((total)).fill(np.NaN),
-                "y2": np.empty((total)).fill(np.NaN),
-            }
-        )
-
-    if isinstance(slides, pd.DataFrame):
-        temp_copy = pd.DataFrame(
-            default_df_dict
-        )  # temporary dataframe w/ default params
-        # find key in provided df
-        # if exist, fill empty fields w/ default values, else, insert the default
-        # values as a new column
-        for key in default_df_dict.keys():
-            if key in slides.columns:
-                mask = slides[key].isna()
-                slides.loc[mask, key] = temp_copy.loc[mask, key]
-            else:
-                slides.insert(len(slides.columns), key, default_df_dict[key])
-    else:
-        slides = pd.DataFrame(default_df_dict)
-
-    return slides
diff --git a/wsinfer/patchlib/wsi_core/util_classes.py b/wsinfer/patchlib/wsi_core/util_classes.py
deleted file mode 100644
index ab5d936..0000000
--- a/wsinfer/patchlib/wsi_core/util_classes.py
+++ /dev/null
@@ -1,164 +0,0 @@
-from __future__ import annotations
-
-import cv2
-import numpy as np
-from PIL import Image
-
-
-class Mosaic_Canvas(object):
-    def __init__(
-        self,
-        patch_size=256,
-        n=100,
-        downscale=4,
-        n_per_row=10,
-        bg_color=(0, 0, 0),
-        alpha=-1,
-    ):
-        self.patch_size = patch_size
-        self.downscaled_patch_size = int(np.ceil(patch_size / downscale))
-        self.n_rows = int(np.ceil(n / n_per_row))
-        self.n_cols = n_per_row
-        w = self.n_cols * self.downscaled_patch_size
-        h = self.n_rows * self.downscaled_patch_size
-        if alpha < 0:
-            canvas = Image.new(size=(w, h), mode="RGB", color=bg_color)
-        else:
-            canvas = Image.new(
-                size=(w, h), mode="RGBA", color=bg_color + (int(255 * alpha),)
-            )
-
-        self.canvas = canvas
-        self.dimensions = np.array([w, h])
-        self.reset_coord()
-
-    def reset_coord(self):
-        self.coord = np.array([0, 0])
-
-    def increment_coord(self):
-        # print('current coord: {} x {} / {} x {}'.format(self.coord[0], self.coord[1],
-        # self.dimensions[0], self.dimensions[1]))
-        assert np.all(self.coord <= self.dimensions)
-        if (
-            self.coord[0] + self.downscaled_patch_size
-            <= self.dimensions[0] - self.downscaled_patch_size
-        ):
-            self.coord[0] += self.downscaled_patch_size
-        else:
-            self.coord[0] = 0
-            self.coord[1] += self.downscaled_patch_size
-
-    def save(self, save_path, **kwargs):
-        self.canvas.save(save_path, **kwargs)
-
-    def paste_patch(self, patch):
-        assert patch.size[0] == self.patch_size
-        assert patch.size[1] == self.patch_size
-        self.canvas.paste(
-            patch.resize(
-                tuple([self.downscaled_patch_size, self.downscaled_patch_size])
-            ),
-            tuple(self.coord),
-        )
-        self.increment_coord()
-
-    def get_painting(self):
-        return self.canvas
-
-
-class Contour_Checking_fn(object):
-    # Defining __call__ method
-    def __call__(self, pt):
-        raise NotImplementedError
-
-
-class isInContourV1(Contour_Checking_fn):
-    def __init__(self, contour):
-        self.cont = contour
-
-    def __call__(self, pt):
-        return (
-            1
-            if cv2.pointPolygonTest(self.cont, tuple(np.array(pt).astype(float)), False)
-            >= 0
-            else 0
-        )
-
-
-class isInContourV2(Contour_Checking_fn):
-    def __init__(self, contour, patch_size):
-        self.cont = contour
-        self.patch_size = patch_size
-
-    def __call__(self, pt):
-        pt = np.array(
-            (pt[0] + self.patch_size // 2, pt[1] + self.patch_size // 2)
-        ).astype(float)
-        return (
-            1
-            if cv2.pointPolygonTest(self.cont, tuple(np.array(pt).astype(float)), False)
-            >= 0
-            else 0
-        )
-
-
-# Easy version of 4pt contour checking function - 1 of 4 points need to be in the
-# contour for test to pass
-class isInContourV3_Easy(Contour_Checking_fn):
-    def __init__(self, contour, patch_size, center_shift=0.5):
-        self.cont = contour
-        self.patch_size = patch_size
-        self.shift = int(patch_size // 2 * center_shift)
-
-    def __call__(self, pt):
-        center = (pt[0] + self.patch_size // 2, pt[1] + self.patch_size // 2)
-        if self.shift > 0:
-            all_points = [
-                (center[0] - self.shift, center[1] - self.shift),
-                (center[0] + self.shift, center[1] + self.shift),
-                (center[0] + self.shift, center[1] - self.shift),
-                (center[0] - self.shift, center[1] + self.shift),
-            ]
-        else:
-            all_points = [center]
-
-        for points in all_points:
-            if (
-                cv2.pointPolygonTest(
-                    self.cont, tuple(np.array(points).astype(float)), False
-                )
-                >= 0
-            ):
-                return 1
-        return 0
-
-
-# Hard version of 4pt contour checking function - all 4 points need to be in the
-# contour for test to pass
-class isInContourV3_Hard(Contour_Checking_fn):
-    def __init__(self, contour, patch_size, center_shift=0.5):
-        self.cont = contour
-        self.patch_size = patch_size
-        self.shift = int(patch_size // 2 * center_shift)
-
-    def __call__(self, pt):
-        center = (pt[0] + self.patch_size // 2, pt[1] + self.patch_size // 2)
-        if self.shift > 0:
-            all_points = [
-                (center[0] - self.shift, center[1] - self.shift),
-                (center[0] + self.shift, center[1] + self.shift),
-                (center[0] + self.shift, center[1] - self.shift),
-                (center[0] - self.shift, center[1] + self.shift),
-            ]
-        else:
-            all_points = [center]
-
-        for points in all_points:
-            if (
-                cv2.pointPolygonTest(
-                    self.cont, tuple(np.array(points).astype(float)), False
-                )
-                < 0
-            ):
-                return 0
-        return 1
diff --git a/wsinfer/patchlib/wsi_core/wsi_utils.py b/wsinfer/patchlib/wsi_core/wsi_utils.py
deleted file mode 100644
index d9eccca..0000000
--- a/wsinfer/patchlib/wsi_core/wsi_utils.py
+++ /dev/null
@@ -1,508 +0,0 @@
-from __future__ import annotations
-
-import math
-import os
-
-import cv2
-import h5py
-import numpy as np
-from PIL import Image
-
-from .util_classes import Mosaic_Canvas
-
-
-def isWhitePatch(patch, satThresh=5):
-    patch_hsv = cv2.cvtColor(patch, cv2.COLOR_RGB2HSV)
-    return True if np.mean(patch_hsv[:, :, 1]) < satThresh else False
-
-
-def isBlackPatch(patch, rgbThresh=40):
-    return True if np.all(np.mean(patch, axis=(0, 1)) < rgbThresh) else False
-
-
-def isBlackPatch_S(patch, rgbThresh=20, percentage=0.05):
-    num_pixels = patch.size[0] * patch.size[1]
-    return (
-        True
-        if np.all(np.array(patch) < rgbThresh, axis=(2)).sum() > num_pixels * percentage
-        else False
-    )
-
-
-def isWhitePatch_S(patch, rgbThresh=220, percentage=0.2):
-    num_pixels = patch.size[0] * patch.size[1]
-    return (
-        True
-        if np.all(np.array(patch) > rgbThresh, axis=(2)).sum() > num_pixels * percentage
-        else False
-    )
-
-
-def coord_generator(x_start, x_end, x_step, y_start, y_end, y_step, args_dict=None):
-    for x in range(x_start, x_end, x_step):
-        for y in range(y_start, y_end, y_step):
-            if args_dict is not None:
-                process_dict = args_dict.copy()
-                process_dict.update({"pt": (x, y)})
-                yield process_dict
-            else:
-                yield (x, y)
-
-
-def savePatchIter_bag_hdf5(patch):
-    (
-        x,
-        y,
-        cont_idx,
-        patch_level,
-        downsample,
-        downsampled_level_dim,
-        level_dim,
-        img_patch,
-        name,
-        save_path,
-    ) = tuple(patch.values())
-    img_patch = np.array(img_patch)[np.newaxis, ...]
-    img_shape = img_patch.shape
-
-    file_path = os.path.join(save_path, name) + ".h5"
-    file = h5py.File(file_path, "a")
-
-    dset = file["imgs"]
-    dset.resize(len(dset) + img_shape[0], axis=0)
-    dset[-img_shape[0] :] = img_patch
-
-    if "coords" in file:
-        coord_dset = file["coords"]
-        coord_dset.resize(len(coord_dset) + img_shape[0], axis=0)
-        coord_dset[-img_shape[0] :] = (x, y)
-
-    file.close()
-
-
-def save_hdf5(output_path, asset_dict, attr_dict=None, mode="a"):
-    file = h5py.File(output_path, mode)
-    for key, val in asset_dict.items():
-        data_shape = val.shape
-        if key not in file:
-            data_type = val.dtype
-            chunk_shape = (1,) + data_shape[1:]
-            maxshape = (None,) + data_shape[1:]
-            dset = file.create_dataset(
-                key,
-                shape=data_shape,
-                maxshape=maxshape,
-                chunks=chunk_shape,
-                dtype=data_type,
-            )
-            dset[:] = val
-            if attr_dict is not None:
-                if key in attr_dict.keys():
-                    for attr_key, attr_val in attr_dict[key].items():
-                        dset.attrs[attr_key] = attr_val
-        else:
-            dset = file[key]
-            dset.resize(len(dset) + data_shape[0], axis=0)
-            dset[-data_shape[0] :] = val
-    file.close()
-    return output_path
-
-
-def initialize_hdf5_bag(first_patch, save_coord=False):
-    (
-        x,
-        y,
-        cont_idx,
-        patch_level,
-        downsample,
-        downsampled_level_dim,
-        level_dim,
-        img_patch,
-        name,
-        save_path,
-    ) = tuple(first_patch.values())
-    file_path = os.path.join(save_path, name) + ".h5"
-    file = h5py.File(file_path, "w")
-    img_patch = np.array(img_patch)[np.newaxis, ...]
-    dtype = img_patch.dtype
-
-    # Initialize a resizable dataset to hold the output
-    img_shape = img_patch.shape
-    maxshape = (None,) + img_shape[
-        1:
-    ]  # maximum dimensions up to which dataset maybe resized (None means unlimited)
-    dset = file.create_dataset(
-        "imgs", shape=img_shape, maxshape=maxshape, chunks=img_shape, dtype=dtype
-    )
-
-    dset[:] = img_patch
-    dset.attrs["patch_level"] = patch_level
-    dset.attrs["wsi_name"] = name
-    dset.attrs["downsample"] = downsample
-    dset.attrs["level_dim"] = level_dim
-    dset.attrs["downsampled_level_dim"] = downsampled_level_dim
-
-    if save_coord:
-        coord_dset = file.create_dataset(
-            "coords", shape=(1, 2), maxshape=(None, 2), chunks=(1, 2), dtype=np.int32
-        )
-        coord_dset[:] = (x, y)
-
-    file.close()
-    return file_path
-
-
-def sample_indices(
-    scores, k, start=0.48, end=0.52, convert_to_percentile=False, seed=1
-):
-    np.random.seed(seed)
-    if convert_to_percentile:
-        end_value = np.quantile(scores, end)
-        start_value = np.quantile(scores, start)
-    else:
-        end_value = end
-        start_value = start
-    score_window = np.logical_and(scores >= start_value, scores <= end_value)
-    indices = np.where(score_window)[0]
-    if len(indices) < 1:
-        return -1
-    else:
-        return np.random.choice(indices, min(k, len(indices)), replace=False)
-
-
-def top_k(scores, k, invert=False):
-    if invert:
-        top_k_ids = scores.argsort()[:k]
-    else:
-        top_k_ids = scores.argsort()[::-1][:k]
-    return top_k_ids
-
-
-def to_percentiles(scores):
-    from scipy.stats import rankdata
-
-    scores = rankdata(scores, "average") / len(scores) * 100
-    return scores
-
-
-def screen_coords(scores, coords, top_left, bot_right):
-    bot_right = np.array(bot_right)
-    top_left = np.array(top_left)
-    mask = np.logical_and(
-        np.all(coords >= top_left, axis=1), np.all(coords <= bot_right, axis=1)
-    )
-    scores = scores[mask]
-    coords = coords[mask]
-    return scores, coords
-
-
-def sample_rois(
-    scores,
-    coords,
-    k=5,
-    mode="range_sample",
-    seed=1,
-    score_start=0.45,
-    score_end=0.55,
-    top_left=None,
-    bot_right=None,
-):
-    if len(scores.shape) == 2:
-        scores = scores.flatten()
-
-    scores = to_percentiles(scores)
-    if top_left is not None and bot_right is not None:
-        scores, coords = screen_coords(scores, coords, top_left, bot_right)
-
-    if mode == "range_sample":
-        sampled_ids = sample_indices(
-            scores,
-            start=score_start,
-            end=score_end,
-            k=k,
-            convert_to_percentile=False,
-            seed=seed,
-        )
-    elif mode == "topk":
-        sampled_ids = top_k(scores, k, invert=False)
-    elif mode == "reverse_topk":
-        sampled_ids = top_k(scores, k, invert=True)
-    else:
-        raise NotImplementedError
-    coords = coords[sampled_ids]
-    scores = scores[sampled_ids]
-
-    asset = {"sampled_coords": coords, "sampled_scores": scores}
-    return asset
-
-
-def DrawGrid(img, coord, shape, thickness=2, color=(0, 0, 0, 255)):
-    cv2.rectangle(
-        img,
-        tuple(np.maximum([0, 0], coord - thickness // 2)),
-        tuple(coord - thickness // 2 + np.array(shape)),
-        (0, 0, 0, 255),
-        thickness=thickness,
-    )
-    return img
-
-
-def DrawMap(
-    canvas, patch_dset, coords, patch_size, indices=None, verbose=1, draw_grid=True
-):
-    if indices is None:
-        indices = np.arange(len(coords))
-    total = len(indices)
-    if verbose > 0:
-        ten_percent_chunk = math.ceil(total * 0.1)
-        print("start stitching {}".format(patch_dset.attrs["wsi_name"]))
-
-    for idx in range(total):
-        if verbose > 0:
-            if idx % ten_percent_chunk == 0:
-                print("progress: {}/{} stitched".format(idx, total))
-
-        patch_id = indices[idx]
-        patch = patch_dset[patch_id]
-        patch = cv2.resize(patch, patch_size)
-        coord = coords[patch_id]
-        canvas_crop_shape = canvas[
-            coord[1] : coord[1] + patch_size[1], coord[0] : coord[0] + patch_size[0], :3
-        ].shape[:2]
-        canvas[
-            coord[1] : coord[1] + patch_size[1], coord[0] : coord[0] + patch_size[0], :3
-        ] = patch[: canvas_crop_shape[0], : canvas_crop_shape[1], :]
-        if draw_grid:
-            DrawGrid(canvas, coord, patch_size)
-
-    return Image.fromarray(canvas)
-
-
-def DrawMapFromCoords(
-    canvas,
-    wsi_object,
-    coords,
-    patch_size,
-    vis_level,
-    indices=None,
-    verbose=1,
-    draw_grid=True,
-):
-    downsamples = wsi_object.wsi.level_downsamples[vis_level]
-    if indices is None:
-        indices = np.arange(len(coords))
-    total = len(indices)
-    if verbose > 0:
-        ten_percent_chunk = math.ceil(total * 0.1)
-
-    patch_size = tuple(
-        np.ceil((np.array(patch_size) / np.array(downsamples))).astype(np.int32)
-    )
-    print("downscaled patch size: {}x{}".format(patch_size[0], patch_size[1]))
-
-    for idx in range(total):
-        if verbose > 0:
-            if idx % ten_percent_chunk == 0:
-                print("progress: {}/{} stitched".format(idx, total))
-
-        patch_id = indices[idx]
-        coord = coords[patch_id]
-        patch = np.array(
-            wsi_object.wsi.read_region(tuple(coord), vis_level, patch_size).convert(
-                "RGB"
-            )
-        )
-        coord = np.ceil(coord / downsamples).astype(np.int32)
-        canvas_crop_shape = canvas[
-            coord[1] : coord[1] + patch_size[1], coord[0] : coord[0] + patch_size[0], :3
-        ].shape[:2]
-        canvas[
-            coord[1] : coord[1] + patch_size[1], coord[0] : coord[0] + patch_size[0], :3
-        ] = patch[: canvas_crop_shape[0], : canvas_crop_shape[1], :]
-        if draw_grid:
-            DrawGrid(canvas, coord, patch_size)
-
-    return Image.fromarray(canvas)
-
-
-def StitchPatches(
-    hdf5_file_path, downscale=16, draw_grid=False, bg_color=(0, 0, 0), alpha=-1
-):
-    file = h5py.File(hdf5_file_path, "r")
-    dset = file["imgs"]
-    coords = file["coords"][:]
-    if "downsampled_level_dim" in dset.attrs.keys():
-        w, h = dset.attrs["downsampled_level_dim"]
-    else:
-        w, h = dset.attrs["level_dim"]
-    print("original size: {} x {}".format(w, h))
-    w = w // downscale
-    h = h // downscale
-    coords = (coords / downscale).astype(np.int32)
-    print("downscaled size for stiching: {} x {}".format(w, h))
-    print("number of patches: {}".format(len(dset)))
-    img_shape = dset[0].shape
-    print("patch shape: {}".format(img_shape))
-    downscaled_shape = (img_shape[1] // downscale, img_shape[0] // downscale)
-
-    if w * h > Image.MAX_IMAGE_PIXELS:
-        raise Image.DecompressionBombError(
-            "Visualization Downscale %d is too large" % downscale
-        )
-
-    if alpha < 0 or alpha == -1:
-        heatmap = Image.new(size=(w, h), mode="RGB", color=bg_color)
-    else:
-        heatmap = Image.new(
-            size=(w, h), mode="RGBA", color=bg_color + (int(255 * alpha),)
-        )
-
-    heatmap = np.array(heatmap)
-    heatmap = DrawMap(
-        heatmap, dset, coords, downscaled_shape, indices=None, draw_grid=draw_grid
-    )
-
-    file.close()
-    return heatmap
-
-
-def StitchCoords(
-    hdf5_file_path,
-    wsi_object,
-    downscale=16,
-    draw_grid=False,
-    bg_color=(0, 0, 0),
-    alpha=-1,
-):
-    wsi = wsi_object.getOpenSlide()
-    vis_level = wsi.get_best_level_for_downsample(downscale)
-    file = h5py.File(hdf5_file_path, "r")
-    dset = file["coords"]
-    coords = dset[:]
-    w, h = wsi.level_dimensions[0]
-
-    print("start stitching {}".format(dset.attrs["name"]))
-    print("original size: {} x {}".format(w, h))
-
-    w, h = wsi.level_dimensions[vis_level]
-
-    print("downscaled size for stiching: {} x {}".format(w, h))
-    print("number of patches: {}".format(len(coords)))
-
-    patch_size = dset.attrs["patch_size"]
-    patch_level = dset.attrs["patch_level"]
-    print(
-        "patch size: {}x{} patch level: {}".format(patch_size, patch_size, patch_level)
-    )
-    patch_size = tuple(
-        (
-            np.array((patch_size, patch_size)) * wsi.level_downsamples[patch_level]
-        ).astype(np.int32)
-    )
-    print("ref patch size: {}x{}".format(patch_size, patch_size))
-
-    if w * h > Image.MAX_IMAGE_PIXELS:
-        raise Image.DecompressionBombError(
-            "Visualization Downscale %d is too large" % downscale
-        )
-
-    if alpha < 0 or alpha == -1:
-        heatmap = Image.new(size=(w, h), mode="RGB", color=bg_color)
-    else:
-        heatmap = Image.new(
-            size=(w, h), mode="RGBA", color=bg_color + (int(255 * alpha),)
-        )
-
-    heatmap = np.array(heatmap)
-    heatmap = DrawMapFromCoords(
-        heatmap,
-        wsi_object,
-        coords,
-        patch_size,
-        vis_level,
-        indices=None,
-        draw_grid=draw_grid,
-    )
-
-    file.close()
-    return heatmap
-
-
-def SamplePatches(
-    coords_file_path,
-    save_file_path,
-    wsi_object,
-    patch_level=0,
-    custom_downsample=1,
-    patch_size=256,
-    sample_num=100,
-    seed=1,
-    stitch=True,
-    verbose=1,
-    mode="w",
-):
-    file = h5py.File(coords_file_path, "r")
-    dset = file["coords"]
-    coords = dset[:]
-
-    h5_patch_size = dset.attrs["patch_size"]
-    h5_patch_level = dset.attrs["patch_level"]
-
-    if verbose > 0:
-        print("in .h5 file: total number of patches: {}".format(len(coords)))
-        print(
-            "in .h5 file: patch size: {}x{} patch level: {}".format(
-                h5_patch_size, h5_patch_size, h5_patch_level
-            )
-        )
-
-    if patch_level < 0:
-        patch_level = h5_patch_level
-
-    if patch_size < 0:
-        patch_size = h5_patch_size
-
-    np.random.seed(seed)
-    indices = np.random.choice(
-        np.arange(len(coords)), min(len(coords), sample_num), replace=False
-    )
-
-    target_patch_size = np.array([patch_size, patch_size])
-
-    if custom_downsample > 1:
-        target_patch_size = (
-            np.array([patch_size, patch_size]) / custom_downsample
-        ).astype(np.int32)
-
-    if stitch:
-        canvas = Mosaic_Canvas(
-            patch_size=target_patch_size[0],
-            n=sample_num,
-            downscale=4,
-            n_per_row=10,
-            bg_color=(0, 0, 0),
-            alpha=-1,
-        )
-    else:
-        canvas = None
-
-    for idx in indices:
-        coord = coords[idx]
-        patch = wsi_object.wsi.read_region(
-            coord, patch_level, tuple([patch_size, patch_size])
-        ).convert("RGB")
-        if custom_downsample > 1:
-            patch = patch.resize(tuple(target_patch_size))
-
-        # if isBlackPatch_S(patch, rgbThresh=20, percentage=0.05) or isWhitePatch_S(
-        # patch, rgbThresh=220, percentage=0.25):
-        #     continue
-
-        if stitch:
-            canvas.paste_patch(patch)
-
-        asset_dict = {"imgs": np.array(patch)[np.newaxis, ...], "coords": coord}
-        save_hdf5(save_file_path, asset_dict, mode=mode)
-        mode = "a"
-
-    return canvas, len(coords), len(indices)


Test patch:
diff --git a/tests/reference/pancancer-lymphocytes-inceptionv4.tcga/purple.csv b/tests/reference/pancancer-lymphocytes-inceptionv4.tcga/purple.csv
index 67f7ee1..e00d4d8 100644
--- a/tests/reference/pancancer-lymphocytes-inceptionv4.tcga/purple.csv
+++ b/tests/reference/pancancer-lymphocytes-inceptionv4.tcga/purple.csv
@@ -19,7 +19,6 @@ minx,miny,width,height,prob_notils,prob_tils
 0,3400,200,200,1.0,3.427372535086404e-12
 0,3600,200,200,1.0,3.427372535086404e-12
 0,3800,200,200,1.0,3.427372535086404e-12
-0,4000,200,200,0.9999136924743652,8.626562339486554e-05
 200,0,200,200,1.0,3.427372535086404e-12
 200,200,200,200,1.0,3.427372535086404e-12
 200,400,200,200,1.0,3.427372535086404e-12
@@ -40,7 +39,6 @@ minx,miny,width,height,prob_notils,prob_tils
 200,3400,200,200,1.0,3.427372535086404e-12
 200,3600,200,200,1.0,3.427372535086404e-12
 200,3800,200,200,1.0,3.427372535086404e-12
-200,4000,200,200,0.9999136924743652,8.626562339486554e-05
 400,0,200,200,1.0,3.427372535086404e-12
 400,200,200,200,1.0,3.427372535086404e-12
 400,400,200,200,1.0,3.427372535086404e-12
@@ -61,7 +59,6 @@ minx,miny,width,height,prob_notils,prob_tils
 400,3400,200,200,1.0,3.427372535086404e-12
 400,3600,200,200,1.0,3.427372535086404e-12
 400,3800,200,200,1.0,3.427372535086404e-12
-400,4000,200,200,0.9999136924743652,8.626562339486554e-05
 600,0,200,200,1.0,3.427372535086404e-12
 600,200,200,200,1.0,3.427372535086404e-12
 600,400,200,200,1.0,3.427372535086404e-12
@@ -82,7 +79,6 @@ minx,miny,width,height,prob_notils,prob_tils
 600,3400,200,200,1.0,3.427372535086404e-12
 600,3600,200,200,1.0,3.427372535086404e-12
 600,3800,200,200,1.0,3.427372535086404e-12
-600,4000,200,200,0.9999136924743652,8.626562339486554e-05
 800,0,200,200,1.0,3.427372535086404e-12
 800,200,200,200,1.0,3.427372535086404e-12
 800,400,200,200,1.0,3.427372535086404e-12
@@ -103,7 +99,6 @@ minx,miny,width,height,prob_notils,prob_tils
 800,3400,200,200,1.0,3.427372535086404e-12
 800,3600,200,200,1.0,3.427372535086404e-12
 800,3800,200,200,1.0,3.427372535086404e-12
-800,4000,200,200,0.9999136924743652,8.626562339486554e-05
 1000,0,200,200,1.0,3.427372535086404e-12
 1000,200,200,200,1.0,3.427372535086404e-12
 1000,400,200,200,1.0,3.427372535086404e-12
@@ -124,7 +119,6 @@ minx,miny,width,height,prob_notils,prob_tils
 1000,3400,200,200,1.0,3.427372535086404e-12
 1000,3600,200,200,1.0,3.427372535086404e-12
 1000,3800,200,200,1.0,3.427372535086404e-12
-1000,4000,200,200,0.9999136924743652,8.626562339486554e-05
 1200,0,200,200,1.0,3.427372535086404e-12
 1200,200,200,200,1.0,3.427372535086404e-12
 1200,400,200,200,1.0,3.427372535086404e-12
@@ -145,7 +139,6 @@ minx,miny,width,height,prob_notils,prob_tils
 1200,3400,200,200,1.0,3.427372535086404e-12
 1200,3600,200,200,1.0,3.427372535086404e-12
 1200,3800,200,200,1.0,3.427372535086404e-12
-1200,4000,200,200,0.9999136924743652,8.626562339486554e-05
 1400,0,200,200,1.0,3.427372535086404e-12
 1400,200,200,200,1.0,3.427372535086404e-12
 1400,400,200,200,1.0,3.427372535086404e-12
@@ -166,7 +159,6 @@ minx,miny,width,height,prob_notils,prob_tils
 1400,3400,200,200,1.0,3.427372535086404e-12
 1400,3600,200,200,1.0,3.427372535086404e-12
 1400,3800,200,200,1.0,3.427372535086404e-12
-1400,4000,200,200,0.9999136924743652,8.626562339486554e-05
 1600,0,200,200,1.0,3.427372535086404e-12
 1600,200,200,200,1.0,3.427372535086404e-12
 1600,400,200,200,1.0,3.427372535086404e-12
@@ -187,7 +179,6 @@ minx,miny,width,height,prob_notils,prob_tils
 1600,3400,200,200,1.0,3.427372535086404e-12
 1600,3600,200,200,1.0,3.427372535086404e-12
 1600,3800,200,200,1.0,3.427372535086404e-12
-1600,4000,200,200,0.9999136924743652,8.626562339486554e-05
 1800,0,200,200,1.0,3.427372535086404e-12
 1800,200,200,200,1.0,3.427372535086404e-12
 1800,400,200,200,1.0,3.427372535086404e-12
@@ -208,7 +199,6 @@ minx,miny,width,height,prob_notils,prob_tils
 1800,3400,200,200,1.0,3.427372535086404e-12
 1800,3600,200,200,1.0,3.427372535086404e-12
 1800,3800,200,200,1.0,3.427372535086404e-12
-1800,4000,200,200,0.9999136924743652,8.626562339486554e-05
 2000,0,200,200,1.0,3.427372535086404e-12
 2000,200,200,200,1.0,3.427372535086404e-12
 2000,400,200,200,1.0,3.427372535086404e-12
@@ -229,7 +219,6 @@ minx,miny,width,height,prob_notils,prob_tils
 2000,3400,200,200,1.0,3.427372535086404e-12
 2000,3600,200,200,1.0,3.427372535086404e-12
 2000,3800,200,200,1.0,3.427372535086404e-12
-2000,4000,200,200,0.9999136924743652,8.626562339486554e-05
 2200,0,200,200,1.0,3.427372535086404e-12
 2200,200,200,200,1.0,3.427372535086404e-12
 2200,400,200,200,1.0,3.427372535086404e-12
@@ -250,7 +239,6 @@ minx,miny,width,height,prob_notils,prob_tils
 2200,3400,200,200,1.0,3.427372535086404e-12
 2200,3600,200,200,1.0,3.427372535086404e-12
 2200,3800,200,200,1.0,3.427372535086404e-12
-2200,4000,200,200,0.9999136924743652,8.626562339486554e-05
 2400,0,200,200,1.0,3.427372535086404e-12
 2400,200,200,200,1.0,3.427372535086404e-12
 2400,400,200,200,1.0,3.427372535086404e-12
@@ -271,7 +259,6 @@ minx,miny,width,height,prob_notils,prob_tils
 2400,3400,200,200,1.0,3.427372535086404e-12
 2400,3600,200,200,1.0,3.427372535086404e-12
 2400,3800,200,200,1.0,3.427372535086404e-12
-2400,4000,200,200,0.9999136924743652,8.626562339486554e-05
 2600,0,200,200,1.0,3.427372535086404e-12
 2600,200,200,200,1.0,3.427372535086404e-12
 2600,400,200,200,1.0,3.427372535086404e-12
@@ -292,7 +279,6 @@ minx,miny,width,height,prob_notils,prob_tils
 2600,3400,200,200,1.0,3.427372535086404e-12
 2600,3600,200,200,1.0,3.427372535086404e-12
 2600,3800,200,200,1.0,3.427372535086404e-12
-2600,4000,200,200,0.9999136924743652,8.626562339486554e-05
 2800,0,200,200,1.0,3.427372535086404e-12
 2800,200,200,200,1.0,3.427372535086404e-12
 2800,400,200,200,1.0,3.427372535086404e-12
@@ -313,7 +299,6 @@ minx,miny,width,height,prob_notils,prob_tils
 2800,3400,200,200,1.0,3.427372535086404e-12
 2800,3600,200,200,1.0,3.427372535086404e-12
 2800,3800,200,200,1.0,3.427372535086404e-12
-2800,4000,200,200,0.9999136924743652,8.626562339486554e-05
 3000,0,200,200,1.0,3.427372535086404e-12
 3000,200,200,200,1.0,3.427372535086404e-12
 3000,400,200,200,1.0,3.427372535086404e-12
@@ -334,7 +319,6 @@ minx,miny,width,height,prob_notils,prob_tils
 3000,3400,200,200,1.0,3.427372535086404e-12
 3000,3600,200,200,1.0,3.427372535086404e-12
 3000,3800,200,200,1.0,3.427372535086404e-12
-3000,4000,200,200,0.9999136924743652,8.626562339486554e-05
 3200,0,200,200,1.0,3.427372535086404e-12
 3200,200,200,200,1.0,3.427372535086404e-12
 3200,400,200,200,1.0,3.427372535086404e-12
@@ -355,7 +339,6 @@ minx,miny,width,height,prob_notils,prob_tils
 3200,3400,200,200,1.0,3.427372535086404e-12
 3200,3600,200,200,1.0,3.427372535086404e-12
 3200,3800,200,200,1.0,3.427372535086404e-12
-3200,4000,200,200,0.9999136924743652,8.626562339486554e-05
 3400,0,200,200,1.0,3.427372535086404e-12
 3400,200,200,200,1.0,3.427372535086404e-12
 3400,400,200,200,1.0,3.427372535086404e-12
@@ -376,7 +359,6 @@ minx,miny,width,height,prob_notils,prob_tils
 3400,3400,200,200,1.0,3.427372535086404e-12
 3400,3600,200,200,1.0,3.427372535086404e-12
 3400,3800,200,200,1.0,3.427372535086404e-12
-3400,4000,200,200,0.9999136924743652,8.626562339486554e-05
 3600,0,200,200,1.0,3.427372535086404e-12
 3600,200,200,200,1.0,3.427372535086404e-12
 3600,400,200,200,1.0,3.427372535086404e-12
@@ -397,7 +379,6 @@ minx,miny,width,height,prob_notils,prob_tils
 3600,3400,200,200,1.0,3.427372535086404e-12
 3600,3600,200,200,1.0,3.427372535086404e-12
 3600,3800,200,200,1.0,3.427372535086404e-12
-3600,4000,200,200,0.9999136924743652,8.626562339486554e-05
 3800,0,200,200,1.0,3.427372535086404e-12
 3800,200,200,200,1.0,3.427372535086404e-12
 3800,400,200,200,1.0,3.427372535086404e-12
@@ -418,25 +399,3 @@ minx,miny,width,height,prob_notils,prob_tils
 3800,3400,200,200,1.0,3.427372535086404e-12
 3800,3600,200,200,1.0,3.427372535086404e-12
 3800,3800,200,200,1.0,3.427372535086404e-12
-3800,4000,200,200,0.9999136924743652,8.626562339486554e-05
-4000,0,200,200,0.9996557235717772,0.0003442850720603
-4000,200,200,200,0.9996557235717772,0.0003442850720603
-4000,400,200,200,0.9996557235717772,0.0003442850720603
-4000,600,200,200,0.9996557235717772,0.0003442850720603
-4000,800,200,200,0.9996557235717772,0.0003442850720603
-4000,1000,200,200,0.9996557235717772,0.0003442850720603
-4000,1200,200,200,0.9996557235717772,0.0003442850720603
-4000,1400,200,200,0.9996557235717772,0.0003442850720603
-4000,1600,200,200,0.9996557235717772,0.0003442850720603
-4000,1800,200,200,0.9996557235717772,0.0003442850720603
-4000,2000,200,200,0.9996557235717772,0.0003442850720603
-4000,2200,200,200,0.9996557235717772,0.0003442850720603
-4000,2400,200,200,0.9996557235717772,0.0003442850720603
-4000,2600,200,200,0.9996557235717772,0.0003442850720603
-4000,2800,200,200,0.9996557235717772,0.0003442850720603
-4000,3000,200,200,0.9996557235717772,0.0003442850720603
-4000,3200,200,200,0.9996557235717772,0.0003442850720603
-4000,3400,200,200,0.9996557235717772,0.0003442850720603
-4000,3600,200,200,0.9996557235717772,0.0003442850720603
-4000,3800,200,200,0.9996557235717772,0.0003442850720603
-4000,4000,200,200,0.9894591569900512,0.0105408066883683
diff --git a/tests/test_all.py b/tests/test_all.py
index 4c63409..0b0c63c 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -291,7 +291,7 @@ def test_convert_to_sbu():
 
 @pytest.mark.parametrize(
     ["patch_size", "patch_spacing"],
-    [(256, 0.25), (256, 0.50), (350, 0.25), (100, 0.3)],
+    [(256, 0.25), (256, 0.50), (350, 0.25), (100, 0.3), (100, 0.5)],
 )
 def test_patch_cli(
     patch_size: int, patch_spacing: float, tmp_path: Path, tiff_image: Path
@@ -306,13 +306,13 @@ def test_patch_cli(
         cli,
         [
             "patch",
-            "--source",
+            "--wsi-dir",
             str(tiff_image.parent),
-            "--save-dir",
+            "--results-dir",
             str(savedir),
-            "--patch-size",
+            "--patch-size-px",
             str(patch_size),
-            "--patch-spacing",
+            "--patch-spacing-um-px",
             str(patch_spacing),
         ],
     )
@@ -320,8 +320,6 @@ def test_patch_cli(
     stem = tiff_image.stem
     assert (savedir / "masks" / f"{stem}.jpg").exists()
     assert (savedir / "patches" / f"{stem}.h5").exists()
-    assert (savedir / "process_list_autogen.csv").exists()
-    assert (savedir / "stitches" / f"{stem}.jpg").exists()
 
     expected_patch_size = round(patch_size * patch_spacing / orig_slide_spacing)
     sqrt_expected_num_patches = round(orig_slide_size / expected_patch_size)