Refactor HVideoTool to support project-based workflow: introduced project management features, updated UI for project handling, and enhanced documentation in README and CLAUDE.md. The tool now organizes images and settings into projects, improving usability and detection caching.

This commit is contained in:
Leonid Pershin
2026-06-07 04:53:27 +03:00
parent 7f0121b7df
commit e27dfdf518
27 changed files with 2998 additions and 387 deletions
+77
View File
@@ -0,0 +1,77 @@
"""Persist detection results for a project.
The detection cache is a JSON file (``detections.json`` at the project root) that
maps each image to its detections so reopening a project doesn't have to re-run
the detector. The cache file lives apart from the images (which sit in the
project's ``frames/`` sub-folder), so the file location and the image base
directory are passed separately.
The cache is tagged with the detector identity (name + model + conf/imgsz); a
mismatch means the cache was produced by a different detector and is ignored
(``load_results`` returns ``None``) rather than shown as if current.
Keys are stored as **basenames**, so the cache survives moving/renaming the
project folder.
"""
from __future__ import annotations
import json
from pathlib import Path
from .types import Detection
_VERSION = 1
def make_key(detector: str, model_path: str | None, yolo_conf: float, yolo_imgsz: int) -> dict:
"""Identity of the detector that produced a cache; cache is only valid for a match."""
return {
"detector": detector,
"model_path": model_path or "",
"yolo_conf": round(float(yolo_conf), 4),
"yolo_imgsz": int(yolo_imgsz),
}
def save_results(cache_file: Path, key: dict, results: dict[str, list[Detection]]) -> bool:
"""Write the cache (basename -> detections) to ``cache_file``. False on failure."""
payload = {
"version": _VERSION,
"key": key,
"results": {
Path(p).name: [d.to_dict() for d in dets]
for p, dets in results.items()
},
}
try:
cache_file.parent.mkdir(parents=True, exist_ok=True)
cache_file.write_text(
json.dumps(payload, ensure_ascii=False), encoding="utf-8"
)
return True
except OSError:
return False
def load_results(cache_file: Path, key: dict, base_dir: Path) -> dict[str, list[Detection]] | None:
"""Load cached detections from ``cache_file`` if present and the detector matches.
Returns a dict keyed by **full path** (``base_dir / basename``), or ``None`` if
there is no cache, it's unreadable, or it was made by a different detector.
"""
if not cache_file.is_file():
return None
try:
payload = json.loads(cache_file.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if payload.get("version") != _VERSION or payload.get("key") != key:
return None
out: dict[str, list[Detection]] = {}
for name, dets in payload.get("results", {}).items():
try:
out[str(base_dir / name)] = [Detection.from_dict(d) for d in dets]
except (KeyError, TypeError, ValueError):
continue # skip a corrupt entry, keep the rest
return out
+148
View File
@@ -0,0 +1,148 @@
"""A HVideoTool *project*: a self-contained folder on disk.
This replaces the old "open a bare folder of images" model. A project is a folder
that holds:
```
MyProject/
├── project.json # version, name, created, source, settings{detector/model/threshold/restore}
├── frames/ # the images (what used to be "the folder")
├── detections.json # the detection cache (basename -> detections, tagged with detector key)
└── collections/ # curation sub-folders (created lazily)
```
The project file carries the **per-project** settings (detector, model, overlay
threshold, restore engine). Global ``settings.json`` only seeds the defaults for
*new* projects; once a project exists it remembers how it was last inspected.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from ..config import AppConfig
PROJECT_FILE = "project.json"
FRAMES_DIR = "frames"
CACHE_FILE = "detections.json"
COLLECTIONS_DIR = "collections"
FAVORITES_DIR = "Избранное" # the single default collection ("в избранное")
_VERSION = 1
# The subset of AppConfig fields a project remembers (mirrored to/from project.json).
_SETTING_KEYS = (
"detector",
"model_path",
"default_threshold",
"restorer",
"dm_dir",
"dm_model",
"dm_python",
"dm_gpu",
)
@dataclass
class Project:
"""A HVideoTool project rooted at ``root`` — the single source of truth for its
on-disk layout and its per-project settings."""
root: Path
name: str
settings: dict = field(default_factory=dict) # subset of AppConfig fields
source: str | None = None # originating video/folder, if any
created: str | None = None
# ----------------------------------------------------------------- paths
@property
def project_file(self) -> Path:
return self.root / PROJECT_FILE
@property
def frames_dir(self) -> Path:
return self.root / FRAMES_DIR
@property
def cache_path(self) -> Path:
return self.root / CACHE_FILE
@property
def collections_dir(self) -> Path:
return self.root / COLLECTIONS_DIR
@property
def favorites_dir(self) -> Path:
"""The single default collection — frames moved "to favorites" land here."""
return self.collections_dir / FAVORITES_DIR
# ------------------------------------------------------------- lifecycle
@classmethod
def create(
cls,
root: Path | str,
name: str | None = None,
settings: dict | None = None,
source: str | None = None,
) -> "Project":
"""Create a new project folder (with ``frames/``) and write ``project.json``."""
root = Path(root)
proj = cls(
root=root,
name=name or root.name,
settings={k: v for k, v in (settings or {}).items() if k in _SETTING_KEYS},
source=source,
created=datetime.now().isoformat(timespec="seconds"),
)
proj.frames_dir.mkdir(parents=True, exist_ok=True)
proj.save()
return proj
@classmethod
def load(cls, path: Path | str) -> "Project":
"""Load a project from its folder or directly from its ``project.json``."""
path = Path(path)
root = path.parent if path.name == PROJECT_FILE else path
data = json.loads((root / PROJECT_FILE).read_text(encoding="utf-8"))
return cls(
root=root,
name=data.get("name", root.name),
settings={k: v for k, v in data.get("settings", {}).items() if k in _SETTING_KEYS},
source=data.get("source"),
created=data.get("created"),
)
@staticmethod
def is_project(path: Path | str) -> bool:
"""True if ``path`` is a project folder (or a ``project.json``)."""
path = Path(path)
if path.name == PROJECT_FILE:
return path.is_file()
return (path / PROJECT_FILE).is_file()
def save(self) -> None:
"""Write ``project.json``."""
payload = {
"version": _VERSION,
"name": self.name,
"created": self.created,
"source": self.source,
"settings": self.settings,
}
self.root.mkdir(parents=True, exist_ok=True)
self.project_file.write_text(
json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8"
)
# ----------------------------------------------------- settings <-> config
def apply_to_config(self, cfg: AppConfig) -> None:
"""Overlay this project's stored settings onto ``cfg`` (mutates it)."""
for key in _SETTING_KEYS:
if key in self.settings:
setattr(cfg, key, self.settings[key])
def update_from_config(self, cfg: AppConfig) -> None:
"""Capture the per-project settings from ``cfg`` into ``self.settings``."""
self.settings = {key: getattr(cfg, key) for key in _SETTING_KEYS}
@@ -0,0 +1,674 @@
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>.
@@ -0,0 +1,16 @@
# Vendored DeepMosaics code
`models/` and `util/` here are copied **verbatim** from DeepMosaics
(https://github.com/HypoX64/DeepMosaics) by HypoX64, licensed **GPL-3.0**
(see `LICENSE`). We use only the per-image mosaic-clean path
(`models.loadmodel`, `models.runmodel`, `util.image_processing`) — loaded
in-process by `hvideotool/core/restore/deepmosaics.py`.
Because this GPL-3.0 code is combined into HVideoTool, the project as a whole is
distributed under **GPL-3.0**.
Model weights (`clean_*.pth`, `mosaic_position.pth`) are NOT included — the user
points the app at their own downloaded weights.
These files are unmodified; this directory is added to `sys.path` at import time
so the original `from models import …` / `import util.…` statements resolve.
@@ -0,0 +1,51 @@
import os
import shutil
def findalldir(rootdir):
dir_list = []
for root,dirs,files in os.walk(rootdir):
for dir in dirs:
dir_list.append(os.path.join(root,dir))
return(dir_list)
def Traversal(filedir):
file_list=[]
dir_list = []
for root,dirs,files in os.walk(filedir):
for file in files:
file_list.append(os.path.join(root,file))
for dir in dirs:
dir_list.append(os.path.join(root,dir))
Traversal(dir)
return file_list,dir_list
def is_img(path):
ext = os.path.splitext(path)[1]
ext = ext.lower()
if ext in ['.jpg','.png','.jpeg','.bmp']:
return True
else:
return False
def is_video(path):
ext = os.path.splitext(path)[1]
ext = ext.lower()
if ext in ['.mp4','.flv','.avi','.mov','.mkv','.wmv','.rmvb']:
return True
else:
return False
def cleanall():
file_list,dir_list = Traversal('./')
for file in file_list:
if ('tmp' in file) | ('pth' in file)|('pycache' in file) | is_video(file) | is_img(file):
if os.path.exists(file):
if 'imgs' not in file:
os.remove(file)
print('remove file:',file)
for dir in dir_list:
if ('tmp'in dir)|('pycache'in dir):
if os.path.exists(dir):
shutil.rmtree(dir)
print('remove dir:',dir)
@@ -0,0 +1,160 @@
import random
import os
from util.mosaic import get_random_parameter
import numpy as np
import torch
import torchvision.transforms as transforms
import cv2
from . import image_processing as impro
from . import degradater
def to_tensor(data,gpu_id):
data = torch.from_numpy(data)
if gpu_id != '-1':
data = data.cuda()
return data
def normalize(data):
'''
normalize to -1 ~ 1
'''
return (data.astype(np.float32)/255.0-0.5)/0.5
def anti_normalize(data):
return np.clip((data*0.5+0.5)*255,0,255).astype(np.uint8)
def tensor2im(image_tensor, gray=False, rgb2bgr = True ,is0_1 = False, batch_index=0):
image_tensor =image_tensor.data
image_numpy = image_tensor[batch_index].cpu().float().numpy()
if not is0_1:
image_numpy = (image_numpy + 1)/2.0
image_numpy = np.clip(image_numpy * 255.0,0,255)
# gray -> output 1ch
if gray:
h, w = image_numpy.shape[1:]
image_numpy = image_numpy.reshape(h,w)
return image_numpy.astype(np.uint8)
# output 3ch
if image_numpy.shape[0] == 1:
image_numpy = np.tile(image_numpy, (3, 1, 1))
image_numpy = image_numpy.transpose((1, 2, 0))
if rgb2bgr and not gray:
image_numpy = image_numpy[...,::-1]-np.zeros_like(image_numpy)
return image_numpy.astype(np.uint8)
def im2tensor(image_numpy, gray=False,bgr2rgb = True, reshape = True, gpu_id = '-1',is0_1 = False):
if gray:
h, w = image_numpy.shape
image_numpy = (image_numpy/255.0-0.5)/0.5
image_tensor = torch.from_numpy(image_numpy).float()
if reshape:
image_tensor = image_tensor.reshape(1,1,h,w)
else:
h, w ,ch = image_numpy.shape
if bgr2rgb:
image_numpy = image_numpy[...,::-1]-np.zeros_like(image_numpy)
if is0_1:
image_numpy = image_numpy/255.0
else:
image_numpy = (image_numpy/255.0-0.5)/0.5
image_numpy = image_numpy.transpose((2, 0, 1))
image_tensor = torch.from_numpy(image_numpy).float()
if reshape:
image_tensor = image_tensor.reshape(1,ch,h,w)
if gpu_id != '-1':
image_tensor = image_tensor.cuda()
return image_tensor
def shuffledata(data,target):
state = np.random.get_state()
np.random.shuffle(data)
np.random.set_state(state)
np.random.shuffle(target)
def random_transform_single_mask(img,out_shape):
out_h,out_w = out_shape
img = cv2.resize(img,(int(out_w*random.uniform(1.1, 1.5)),int(out_h*random.uniform(1.1, 1.5))))
h,w = img.shape[:2]
h_move = int((h-out_h)*random.random())
w_move = int((w-out_w)*random.random())
img = img[h_move:h_move+out_h,w_move:w_move+out_w]
if random.random()<0.5:
if random.random()<0.5:
img = img[:,::-1]
else:
img = img[::-1,:]
if img.shape[0] != out_h or img.shape[1]!= out_w :
img = cv2.resize(img,(out_w,out_h))
return img
def get_transform_params():
crop_flag = True
rotat_flag = np.random.random()<0.2
color_flag = True
flip_flag = np.random.random()<0.2
degradate_flag = np.random.random()<0.5
flag_dict = {'crop':crop_flag,'rotat':rotat_flag,'color':color_flag,'flip':flip_flag,'degradate':degradate_flag}
crop_rate = [np.random.random(),np.random.random()]
rotat_rate = np.random.random()
color_rate = [np.random.uniform(-0.05,0.05),np.random.uniform(-0.05,0.05),np.random.uniform(-0.05,0.05),
np.random.uniform(-0.05,0.05),np.random.uniform(-0.05,0.05)]
flip_rate = np.random.random()
degradate_params = degradater.get_random_degenerate_params(mod='weaker_2')
rate_dict = {'crop':crop_rate,'rotat':rotat_rate,'color':color_rate,'flip':flip_rate,'degradate':degradate_params}
return {'flag':flag_dict,'rate':rate_dict}
def random_transform_single_image(img,finesize,params=None,test_flag = False):
if params is None:
params = get_transform_params()
if params['flag']['degradate']:
img = degradater.degradate(img,params['rate']['degradate'])
if params['flag']['crop']:
h,w = img.shape[:2]
h_move = int((h-finesize)*params['rate']['crop'][0])
w_move = int((w-finesize)*params['rate']['crop'][1])
img = img[h_move:h_move+finesize,w_move:w_move+finesize]
if test_flag:
return img
if params['flag']['rotat']:
h,w = img.shape[:2]
M = cv2.getRotationMatrix2D((w/2,h/2),90*int(4*params['rate']['rotat']),1)
img = cv2.warpAffine(img,M,(w,h))
if params['flag']['color']:
img = impro.color_adjust(img,params['rate']['color'][0],params['rate']['color'][1],
params['rate']['color'][2],params['rate']['color'][3],params['rate']['color'][4])
if params['flag']['flip']:
img = img[:,::-1]
#check shape
if img.shape[0]!= finesize or img.shape[1]!= finesize:
img = cv2.resize(img,(finesize,finesize))
print('warning! shape error.')
return img
def random_transform_pair_image(img,mask,finesize,test_flag = False):
params = get_transform_params()
img = random_transform_single_image(img,finesize,params)
params['flag']['degradate'] = False
params['flag']['color'] = False
mask = random_transform_single_image(mask,finesize,params)
return img,mask
def showresult(img1,img2,img3,name,is0_1 = False):
size = img1.shape[3]
showimg=np.zeros((size,size*3,3))
showimg[0:size,0:size] = tensor2im(img1,rgb2bgr = False, is0_1 = is0_1)
showimg[0:size,size:size*2] = tensor2im(img2,rgb2bgr = False, is0_1 = is0_1)
showimg[0:size,size*2:size*3] = tensor2im(img3,rgb2bgr = False, is0_1 = is0_1)
cv2.imwrite(name, showimg)
@@ -0,0 +1,141 @@
import os
import random
import numpy as np
from multiprocessing import Process, Queue
from . import image_processing as impro
from . import mosaic,data
class VideoLoader(object):
"""docstring for VideoLoader
Load a single video(Converted to images)
How to use:
1.Init VideoLoader as loader
2.Get data by loader.ori_stream
3.loader.next() to get next stream
"""
def __init__(self, opt, video_dir, test_flag=False):
super(VideoLoader, self).__init__()
self.opt = opt
self.test_flag = test_flag
self.video_dir = video_dir
self.t = 0
self.n_iter = self.opt.M -self.opt.S*(self.opt.T+1)
self.transform_params = data.get_transform_params()
self.ori_load_pool = []
self.mosaic_load_pool = []
self.previous_pred = None
feg_ori = impro.imread(os.path.join(video_dir,'origin_image','00001.jpg'),loadsize=self.opt.loadsize,rgb=True)
feg_mask = impro.imread(os.path.join(video_dir,'mask','00001.png'),mod='gray',loadsize=self.opt.loadsize)
self.mosaic_size,self.mod,self.rect_rat,self.feather = mosaic.get_random_parameter(feg_ori,feg_mask)
self.startpos = [random.randint(0,self.mosaic_size),random.randint(0,self.mosaic_size)]
self.loadsize = self.opt.loadsize
#Init load pool
for i in range(self.opt.S*self.opt.T):
_ori_img = impro.imread(os.path.join(video_dir,'origin_image','%05d' % (i+1)+'.jpg'),loadsize=self.loadsize,rgb=True)
_mask = impro.imread(os.path.join(video_dir,'mask','%05d' % (i+1)+'.png' ),mod='gray',loadsize=self.loadsize)
_mosaic_img = mosaic.addmosaic_base(_ori_img, _mask, self.mosaic_size,0, self.mod,self.rect_rat,self.feather,self.startpos)
_ori_img = data.random_transform_single_image(_ori_img,opt.finesize,self.transform_params)
_mosaic_img = data.random_transform_single_image(_mosaic_img,opt.finesize,self.transform_params)
self.ori_load_pool.append(self.normalize(_ori_img))
self.mosaic_load_pool.append(self.normalize(_mosaic_img))
self.ori_load_pool = np.array(self.ori_load_pool)
self.mosaic_load_pool = np.array(self.mosaic_load_pool)
#Init frist stream
self.ori_stream = self.ori_load_pool [np.linspace(0, (self.opt.T-1)*self.opt.S,self.opt.T,dtype=np.int64)].copy()
self.mosaic_stream = self.mosaic_load_pool[np.linspace(0, (self.opt.T-1)*self.opt.S,self.opt.T,dtype=np.int64)].copy()
# stream B,T,H,W,C -> B,C,T,H,W
self.ori_stream = self.ori_stream.reshape (1,self.opt.T,opt.finesize,opt.finesize,3).transpose((0,4,1,2,3))
self.mosaic_stream = self.mosaic_stream.reshape(1,self.opt.T,opt.finesize,opt.finesize,3).transpose((0,4,1,2,3))
#Init frist previous frame
self.previous_pred = self.ori_load_pool[self.opt.S*self.opt.N-1].copy()
# previous B,C,H,W
self.previous_pred = self.previous_pred.reshape(1,opt.finesize,opt.finesize,3).transpose((0,3,1,2))
def normalize(self,data):
'''
normalize to -1 ~ 1
'''
return (data.astype(np.float32)/255.0-0.5)/0.5
def anti_normalize(self,data):
return np.clip((data*0.5+0.5)*255,0,255).astype(np.uint8)
def next(self):
# random
if np.random.random()<0.05:
self.startpos = [random.randint(0,self.mosaic_size),random.randint(0,self.mosaic_size)]
if np.random.random()<0.02:
self.transform_params['rate']['crop'] = [np.random.random(),np.random.random()]
if np.random.random()<0.02:
self.loadsize = np.random.randint(self.opt.finesize,self.opt.loadsize)
if self.t != 0:
self.previous_pred = None
self.ori_load_pool [:self.opt.S*self.opt.T-1] = self.ori_load_pool [1:self.opt.S*self.opt.T]
self.mosaic_load_pool[:self.opt.S*self.opt.T-1] = self.mosaic_load_pool[1:self.opt.S*self.opt.T]
#print(os.path.join(self.video_dir,'origin_image','%05d' % (self.opt.S*self.opt.T+self.t)+'.jpg'))
_ori_img = impro.imread(os.path.join(self.video_dir,'origin_image','%05d' % (self.opt.S*self.opt.T+self.t)+'.jpg'),loadsize=self.loadsize,rgb=True)
_mask = impro.imread(os.path.join(self.video_dir,'mask','%05d' % (self.opt.S*self.opt.T+self.t)+'.png' ),mod='gray',loadsize=self.loadsize)
_mosaic_img = mosaic.addmosaic_base(_ori_img, _mask, self.mosaic_size,0, self.mod,self.rect_rat,self.feather,self.startpos)
_ori_img = data.random_transform_single_image(_ori_img,self.opt.finesize,self.transform_params)
_mosaic_img = data.random_transform_single_image(_mosaic_img,self.opt.finesize,self.transform_params)
_ori_img,_mosaic_img = self.normalize(_ori_img),self.normalize(_mosaic_img)
self.ori_load_pool [self.opt.S*self.opt.T-1] = _ori_img
self.mosaic_load_pool[self.opt.S*self.opt.T-1] = _mosaic_img
self.ori_stream = self.ori_load_pool [np.linspace(0, (self.opt.T-1)*self.opt.S,self.opt.T,dtype=np.int64)].copy()
self.mosaic_stream = self.mosaic_load_pool[np.linspace(0, (self.opt.T-1)*self.opt.S,self.opt.T,dtype=np.int64)].copy()
# stream B,T,H,W,C -> B,C,T,H,W
self.ori_stream = self.ori_stream.reshape (1,self.opt.T,self.opt.finesize,self.opt.finesize,3).transpose((0,4,1,2,3))
self.mosaic_stream = self.mosaic_stream.reshape(1,self.opt.T,self.opt.finesize,self.opt.finesize,3).transpose((0,4,1,2,3))
self.t += 1
class VideoDataLoader(object):
"""VideoDataLoader"""
def __init__(self, opt, videolist, test_flag=False):
super(VideoDataLoader, self).__init__()
self.videolist = []
self.opt = opt
self.test_flag = test_flag
for i in range(self.opt.n_epoch):
self.videolist += videolist.copy()
random.shuffle(self.videolist)
self.each_video_n_iter = self.opt.M -self.opt.S*(self.opt.T+1)
self.n_iter = len(self.videolist)//self.opt.load_thread//self.opt.batchsize*self.each_video_n_iter*self.opt.load_thread
self.queue = Queue(self.opt.load_thread)
self.ori_stream = np.zeros((self.opt.batchsize,3,self.opt.T,self.opt.finesize,self.opt.finesize),dtype=np.float32)# B,C,T,H,W
self.mosaic_stream = np.zeros((self.opt.batchsize,3,self.opt.T,self.opt.finesize,self.opt.finesize),dtype=np.float32)# B,C,T,H,W
self.previous_pred = np.zeros((self.opt.batchsize,3,self.opt.finesize,self.opt.finesize),dtype=np.float32)
self.load_init()
def load(self,videolist):
for load_video_iter in range(len(videolist)//self.opt.batchsize):
iter_videolist = videolist[load_video_iter*self.opt.batchsize:(load_video_iter+1)*self.opt.batchsize]
videoloaders = [VideoLoader(self.opt,os.path.join(self.opt.dataset,iter_videolist[i]),self.test_flag) for i in range(self.opt.batchsize)]
for each_video_iter in range(self.each_video_n_iter):
for i in range(self.opt.batchsize):
self.ori_stream[i] = videoloaders[i].ori_stream
self.mosaic_stream[i] = videoloaders[i].mosaic_stream
if each_video_iter == 0:
self.previous_pred[i] = videoloaders[i].previous_pred
videoloaders[i].next()
if each_video_iter == 0:
self.queue.put([self.ori_stream.copy(),self.mosaic_stream.copy(),self.previous_pred])
else:
self.queue.put([self.ori_stream.copy(),self.mosaic_stream.copy(),None])
def load_init(self):
ptvn = len(self.videolist)//self.opt.load_thread #pre_thread_video_num
for i in range(self.opt.load_thread):
p = Process(target=self.load,args=(self.videolist[i*ptvn:(i+1)*ptvn],))
p.daemon = True
p.start()
def get_data(self):
return self.queue.get()
@@ -0,0 +1,119 @@
'''
https://github.com/sonack/GFRNet_pytorch_new
'''
import random
import cv2
import numpy as np
def gaussian_blur(img, sigma=3, size=13):
if sigma > 0:
if isinstance(size, int):
size = (size, size)
img = cv2.GaussianBlur(img, size, sigma)
return img
def down(img, scale, shape):
if scale > 1:
h, w, _ = shape
scaled_h, scaled_w = int(h / scale), int(w / scale)
img = cv2.resize(img, (scaled_w, scaled_h), interpolation = cv2.INTER_CUBIC)
return img
def up(img, scale, shape):
if scale > 1:
h, w, _ = shape
img = cv2.resize(img, (w, h), interpolation = cv2.INTER_CUBIC)
return img
def awgn(img, level):
if level > 0:
noise = np.random.randn(*img.shape) * level
img = (img + noise).clip(0,255).astype(np.uint8)
return img
def jpeg_compressor(img,quality):
if quality > 0: # 0 indicating no lossy compression (i.e losslessly compression)
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
img = cv2.imdecode(cv2.imencode('.jpg', img, encode_param)[1], 1)
return img
def get_random_degenerate_params(mod='strong'):
'''
mod : strong | only_downsample | only_4x | weaker_1 | weaker_2
'''
params = {}
gaussianBlur_size_list = list(range(3,14,2))
if mod == 'strong':
gaussianBlur_sigma_list = [1 + x for x in range(3)]
gaussianBlur_sigma_list += [0]
downsample_scale_list = [1 + x * 0.1 for x in range(0,71)]
awgn_level_list = list(range(1, 8, 1))
jpeg_quality_list = list(range(10, 41, 1))
jpeg_quality_list += int(len(jpeg_quality_list) * 0.33) * [0]
elif mod == 'only_downsample':
gaussianBlur_sigma_list = [0]
downsample_scale_list = [1 + x * 0.1 for x in range(0,71)]
awgn_level_list = [0]
jpeg_quality_list = [0]
elif mod == 'only_4x':
gaussianBlur_sigma_list = [0]
downsample_scale_list = [4]
awgn_level_list = [0]
jpeg_quality_list = [0]
elif mod == 'weaker_1': # 0.5 trigger prob
gaussianBlur_sigma_list = [1 + x for x in range(3)]
gaussianBlur_sigma_list += int(len(gaussianBlur_sigma_list)) * [0] # 1/2 trigger this degradation
downsample_scale_list = [1 + x * 0.1 for x in range(0,71)]
downsample_scale_list += int(len(downsample_scale_list)) * [1]
awgn_level_list = list(range(1, 8, 1))
awgn_level_list += int(len(awgn_level_list)) * [0]
jpeg_quality_list = list(range(10, 41, 1))
jpeg_quality_list += int(len(jpeg_quality_list)) * [0]
elif mod == 'weaker_2': # weaker than weaker_1, jpeg [20,40]
gaussianBlur_sigma_list = [1 + x for x in range(3)]
gaussianBlur_sigma_list += int(len(gaussianBlur_sigma_list)) * [0] # 1/2 trigger this degradation
downsample_scale_list = [1 + x * 0.1 for x in range(0,71)]
downsample_scale_list += int(len(downsample_scale_list)) * [1]
awgn_level_list = list(range(1, 8, 1))
awgn_level_list += int(len(awgn_level_list)) * [0]
jpeg_quality_list = list(range(20, 41, 1))
jpeg_quality_list += int(len(jpeg_quality_list)) * [0]
params['blur_sigma'] = random.choice(gaussianBlur_sigma_list)
params['blur_size'] = random.choice(gaussianBlur_size_list)
params['updown_scale'] = random.choice(downsample_scale_list)
params['awgn_level'] = random.choice(awgn_level_list)
params['jpeg_quality'] = random.choice(jpeg_quality_list)
return params
def degradate(img,params,jpeg_last = True):
shape = img.shape
if not params:
params = get_random_degenerate_params('original')
if jpeg_last:
img = gaussian_blur(img,params['blur_sigma'],params['blur_size'])
img = down(img,params['updown_scale'],shape)
img = awgn(img,params['awgn_level'])
img = up(img,params['updown_scale'],shape)
img = jpeg_compressor(img,params['jpeg_quality'])
else:
img = gaussian_blur(img,params['blur_sigma'],params['blur_size'])
img = down(img,params['updown_scale'],shape)
img = awgn(img,params['awgn_level'])
img = jpeg_compressor(img,params['jpeg_quality'])
img = up(img,params['updown_scale'],shape)
return img
@@ -0,0 +1,92 @@
import os,json
import subprocess
# ffmpeg 3.4.6
def args2cmd(args):
cmd = ''
for arg in args:
cmd += (arg+' ')
return cmd
def run(args,mode = 0):
if mode == 0:
cmd = args2cmd(args)
os.system(cmd)
elif mode == 1:
'''
out_string = os.popen(cmd_str).read()
For chinese path in Windows
https://blog.csdn.net/weixin_43903378/article/details/91979025
'''
cmd = args2cmd(args)
stream = os.popen(cmd)._stream
sout = stream.buffer.read().decode(encoding='utf-8')
return sout
elif mode == 2:
cmd = args2cmd(args)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
sout = p.stdout.readlines()
return sout
def video2image(videopath, imagepath, fps=0, start_time='00:00:00', last_time='00:00:00'):
args = ['ffmpeg']
if last_time != '00:00:00':
args += ['-ss', start_time]
args += ['-t', last_time]
args += ['-i', '"'+videopath+'"']
if fps != 0:
args += ['-r', str(fps)]
args += ['-f', 'image2','-q:v','-0',imagepath]
run(args)
def video2voice(videopath, voicepath, start_time='00:00:00', last_time='00:00:00'):
args = ['ffmpeg', '-i', '"'+videopath+'"','-async 1 -f mp3','-b:a 320k']
if last_time != '00:00:00':
args += ['-ss', start_time]
args += ['-t', last_time]
args += [voicepath]
run(args)
def image2video(fps,imagepath,voicepath,videopath):
os.system('ffmpeg -y -r '+str(fps)+' -i '+imagepath+' -vcodec libx264 '+os.path.split(voicepath)[0]+'/video_tmp.mp4')
if os.path.exists(voicepath):
os.system('ffmpeg -i '+os.path.split(voicepath)[0]+'/video_tmp.mp4'+' -i "'+voicepath+'" -vcodec copy -acodec aac '+videopath)
else:
os.system('ffmpeg -i '+os.path.split(voicepath)[0]+'/video_tmp.mp4 '+videopath)
def get_video_infos(videopath):
args = ['ffprobe -v quiet -print_format json -show_format -show_streams', '-i', '"'+videopath+'"']
out_string = run(args,mode=1)
infos = json.loads(out_string)
try:
fps = eval(infos['streams'][0]['avg_frame_rate'])
endtime = float(infos['format']['duration'])
width = int(infos['streams'][0]['width'])
height = int(infos['streams'][0]['height'])
except Exception as e:
fps = eval(infos['streams'][1]['r_frame_rate'])
endtime = float(infos['format']['duration'])
width = int(infos['streams'][1]['width'])
height = int(infos['streams'][1]['height'])
return fps,endtime,height,width
def cut_video(in_path,start_time,last_time,out_path,vcodec='h265'):
if vcodec == 'copy':
os.system('ffmpeg -ss '+start_time+' -t '+last_time+' -i "'+in_path+'" -vcodec copy -acodec copy '+out_path)
elif vcodec == 'h264':
os.system('ffmpeg -ss '+start_time+' -t '+last_time+' -i "'+in_path+'" -vcodec libx264 -b 12M '+out_path)
elif vcodec == 'h265':
os.system('ffmpeg -ss '+start_time+' -t '+last_time+' -i "'+in_path+'" -vcodec libx265 -b 12M '+out_path)
def continuous_screenshot(videopath,savedir,fps):
'''
videopath: input video path
savedir: images will save here
fps: save how many images per second
'''
videoname = os.path.splitext(os.path.basename(videopath))[0]
os.system('ffmpeg -i "'+videopath+'" -vf fps='+str(fps)+' -q:v -0 '+savedir+'/'+videoname+'_%06d.jpg')
@@ -0,0 +1,77 @@
import numpy as np
def less_zero(arr,num = 7):
index = np.linspace(0,len(arr)-1,len(arr),dtype='int')
cnt = 0
for i in range(2,len(arr)-2):
if arr[i] != 0:
arr[i] = arr[i]
if cnt != 0:
if cnt <= num*2:
arr[i-cnt:round(i-cnt/2)] = arr[i-cnt-1-2]
arr[round(i-cnt/2):i] = arr[i+2]
index[i-cnt:round(i-cnt/2)] = i-cnt-1-2
index[round(i-cnt/2):i] = i+2
else:
arr[i-cnt:i-cnt+num] = arr[i-cnt-1-2]
arr[i-num:i] = arr[i+2]
index[i-cnt:i-cnt+num] = i-cnt-1-2
index[i-num:i] = i+2
cnt = 0
else:
cnt += 1
return arr,index
def medfilt(data,window):
if window%2 == 0 or window < 0:
print('Error: the medfilt window must be even number')
exit(0)
pad = int((window-1)/2)
pad_data = np.zeros(len(data)+window-1, dtype = type(data[0]))
result = np.zeros(len(data),dtype = type(data[0]))
pad_data[pad:pad+len(data)]=data[:]
for i in range(len(data)):
result[i] = np.median(pad_data[i:i+window])
return result
def position_medfilt(positions,window):
x,mask_index = less_zero(positions[:,0],window)
y = less_zero(positions[:,1],window)[0]
area = less_zero(positions[:,2],window)[0]
x_filt = medfilt(x, window)
y_filt = medfilt(y, window)
area_filt = medfilt(area, window)
cnt = 0
for i in range(1,len(x)):
if 0.8<x_filt[i]/(x[i]+1)<1.2 and 0.8<y_filt[i]/(y[i]+1)<1.2 and 0.6<area_filt[i]/(area[i]+1)<1.4:
mask_index[i] = mask_index[i]
if cnt != 0:
mask_index[i-cnt:round(i-cnt/2)] = mask_index[i-cnt]
mask_index[round(i-cnt/2):i] = mask_index[i]
cnt = 0
else:
mask_index[i] = mask_index[i-1]
cnt += 1
return mask_index
# def main():
# import matplotlib.pyplot as plt
# positions = np.load('../test_pos.npy')
# positions_new = np.load('../test_pos.npy')
# print(positions.shape)
# mask_index = position_medfilt(positions.copy(), 7)
# x = positions_new[2]
# x_new = []
# for i in range(len(x)):
# x_new.append(x[mask_index[i]])
# plt.subplot(211)
# plt.plot(x)
# plt.subplot(212)
# plt.plot(x_new)
# plt.show()
# if __name__ == '__main__':
# main()
@@ -0,0 +1,253 @@
import cv2
import numpy as np
import random
from threading import Thread
import platform
system_type = 'Linux'
if 'Windows' in platform.platform():
system_type = 'Windows'
def imread(file_path,mod = 'normal',loadsize = 0, rgb=False):
'''
mod: 'normal' | 'gray' | 'all'
loadsize: 0->original
'''
if system_type == 'Linux':
if mod == 'normal':
img = cv2.imread(file_path,1)
elif mod == 'gray':
img = cv2.imread(file_path,0)
elif mod == 'all':
img = cv2.imread(file_path,-1)
#In windows, for chinese path, use cv2.imdecode insteaded.
#It will loss EXIF, I can't fix it
else:
if mod == 'normal':
img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),1)
elif mod == 'gray':
img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),0)
elif mod == 'all':
img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
if loadsize != 0:
img = resize(img, loadsize, interpolation=cv2.INTER_CUBIC)
if rgb and img.ndim==3:
img = img[:,:,::-1]
return img
def imwrite(file_path,img,use_thread=False):
'''
in other to save chinese path images in windows,
this fun just for save final output images
'''
def subfun(file_path,img):
if system_type == 'Linux':
cv2.imwrite(file_path, img)
else:
cv2.imencode('.jpg', img)[1].tofile(file_path)
if use_thread:
t = Thread(target=subfun,args=(file_path, img,))
t.daemon()
t.start
else:
subfun(file_path,img)
def resize(img,size,interpolation=cv2.INTER_LINEAR):
'''
cv2.INTER_NEAREST      最邻近插值点法
cv2.INTER_LINEAR        双线性插值法
cv2.INTER_AREA         邻域像素再取样插补
cv2.INTER_CUBIC        双立方插补,4*4大小的补点
cv2.INTER_LANCZOS4 8x8像素邻域的Lanczos插值
'''
h, w = img.shape[:2]
if np.min((w,h)) ==size:
return img
if w >= h:
res = cv2.resize(img,(int(size*w/h), size),interpolation=interpolation)
else:
res = cv2.resize(img,(size, int(size*h/w)),interpolation=interpolation)
return res
def resize_like(img,img_like):
h, w = img_like.shape[:2]
img = cv2.resize(img, (w,h))
return img
def ch_one2three(img):
res = cv2.merge([img, img, img])
return res
def color_adjust(img,alpha=0,beta=0,b=0,g=0,r=0,ran = False):
'''
g(x) = (1+α)g(x)+255*β,
g(x) = g(x[:+b*255,:+g*255,:+r*255])
Args:
img : input image
alpha : contrast
beta : brightness
b : blue hue
g : green hue
r : red hue
ran : if True, randomly generated color correction parameters
Retuens:
img : output image
'''
img = img.astype('float')
if ran:
alpha = random.uniform(-0.1,0.1)
beta = random.uniform(-0.1,0.1)
b = random.uniform(-0.05,0.05)
g = random.uniform(-0.05,0.05)
r = random.uniform(-0.05,0.05)
img = (1+alpha)*img+255.0*beta
bgr = [b*255.0,g*255.0,r*255.0]
for i in range(3): img[:,:,i]=img[:,:,i]+bgr[i]
return (np.clip(img,0,255)).astype('uint8')
def CAdaIN(src,dst):
'''
make src has dst's style
'''
return np.std(dst)*((src-np.mean(src))/np.std(src))+np.mean(dst)
def makedataset(target_image,orgin_image):
target_image = resize(target_image,256)
orgin_image = resize(orgin_image,256)
img = np.zeros((256,512,3), dtype = "uint8")
w = orgin_image.shape[1]
img[0:256,0:256] = target_image[0:256,int(w/2-256/2):int(w/2+256/2)]
img[0:256,256:512] = orgin_image[0:256,int(w/2-256/2):int(w/2+256/2)]
return img
def find_mostlikely_ROI(mask):
contours,hierarchy=cv2.findContours(mask, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
if len(contours)>0:
areas = []
for contour in contours:
areas.append(cv2.contourArea(contour))
index = areas.index(max(areas))
mask = np.zeros_like(mask)
mask = cv2.fillPoly(mask,[contours[index]],(255))
return mask
def boundingSquare(mask,Ex_mul):
# thresh = mask_threshold(mask,10,threshold)
area = mask_area(mask)
if area == 0 :
return 0,0,0,0
x,y,w,h = cv2.boundingRect(mask)
center = np.array([int(x+w/2),int(y+h/2)])
size = max(w,h)
point0=np.array([x,y])
point1=np.array([x+size,y+size])
h, w = mask.shape[:2]
if size*Ex_mul > min(h, w):
size = min(h, w)
halfsize = int(min(h, w)/2)
else:
size = Ex_mul*size
halfsize = int(size/2)
size = halfsize*2
point0 = center - halfsize
point1 = center + halfsize
if point0[0]<0:
point0[0]=0
point1[0]=size
if point0[1]<0:
point0[1]=0
point1[1]=size
if point1[0]>w:
point1[0]=w
point0[0]=w-size
if point1[1]>h:
point1[1]=h
point0[1]=h-size
center = ((point0+point1)/2).astype('int')
return center[0],center[1],halfsize,area
def mask_threshold(mask,ex_mun,threshold):
mask = cv2.threshold(mask,threshold,255,cv2.THRESH_BINARY)[1]
mask = cv2.blur(mask, (ex_mun, ex_mun))
mask = cv2.threshold(mask,threshold/5,255,cv2.THRESH_BINARY)[1]
return mask
def mask_area(mask):
mask = cv2.threshold(mask,127,255,0)[1]
# contours= cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[1] #for opencv 3.4
contours= cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[0]#updata to opencv 4.0
try:
area = cv2.contourArea(contours[0])
except:
area = 0
return area
def replace_mosaic(img_origin,img_fake,mask,x,y,size,no_feather):
img_fake = cv2.resize(img_fake,(size*2,size*2),interpolation=cv2.INTER_CUBIC)
if no_feather:
img_origin[y-size:y+size,x-size:x+size]=img_fake
return img_origin
else:
# #color correction
# RGB_origin = img_origin[y-size:y+size,x-size:x+size].mean(0).mean(0)
# RGB_fake = img_fake.mean(0).mean(0)
# for i in range(3):img_fake[:,:,i] = np.clip(img_fake[:,:,i]+RGB_origin[i]-RGB_fake[i],0,255)
#eclosion
eclosion_num = int(size/10)+2
mask_crop = cv2.resize(mask,(img_origin.shape[1],img_origin.shape[0]))[y-size:y+size,x-size:x+size]
mask_crop = ch_one2three(mask_crop)
mask_crop = (cv2.blur(mask_crop, (eclosion_num, eclosion_num)))
mask_crop = mask_crop/255.0
img_crop = img_origin[y-size:y+size,x-size:x+size]
img_origin[y-size:y+size,x-size:x+size] = np.clip((img_crop*(1-mask_crop)+img_fake*mask_crop),0,255).astype('uint8')
return img_origin
def Q_lapulase(resImg):
'''
Evaluate image quality
score > 20 normal
score > 50 clear
'''
img2gray = cv2.cvtColor(resImg, cv2.COLOR_BGR2GRAY)
img2gray = resize(img2gray,512)
res = cv2.Laplacian(img2gray, cv2.CV_64F)
score = res.var()
return score
def psnr(img1,img2):
mse = np.mean((img1/255.0-img2/255.0)**2)
if mse < 1e-10:
return 100
psnr_v = 20*np.log10(1/np.sqrt(mse))
return psnr_v
def splice(imgs,splice_shape):
'''Stitching multiple images, all imgs must have the same size
imgs : [img1,img2,img3,img4]
splice_shape: (2,2)
'''
h,w,ch = imgs[0].shape
output = np.zeros((h*splice_shape[0],w*splice_shape[1],ch),np.uint8)
cnt = 0
for i in range(splice_shape[0]):
for j in range(splice_shape[1]):
if cnt < len(imgs):
output[h*i:h*(i+1),w*j:w*(j+1)] = imgs[cnt]
cnt += 1
return output
@@ -0,0 +1,164 @@
import cv2
import numpy as np
import os
import random
from .image_processing import resize,ch_one2three,mask_area
def addmosaic(img,mask,opt):
if opt.mosaic_mod == 'random':
img = addmosaic_random(img,mask)
elif opt.mosaic_size == 0:
img = addmosaic_autosize(img, mask, opt.mosaic_mod)
else:
img = addmosaic_base(img,mask,opt.mosaic_size,opt.output_size,model = opt.mosaic_mod)
return img
def addmosaic_base(img,mask,n,out_size = 0,model = 'squa_avg',rect_rat = 1.6,feather=0,start_point=[0,0]):
'''
img: input image
mask: input mask
n: mosaic size
out_size: output size 0->original
model : squa_avg squa_mid squa_random squa_avg_circle_edge rect_avg
rect_rat: if model==rect_avg , mosaic w/h=rect_rat
feather : feather size, -1->no 0->auto
start_point : [0,0], please not input this parameter
'''
n = int(n)
h_start = np.clip(start_point[0], 0, n)
w_start = np.clip(start_point[1], 0, n)
pix_mid_h = n//2+h_start
pix_mid_w = n//2+w_start
h, w = img.shape[:2]
h_step = (h-h_start)//n
w_step = (w-w_start)//n
if out_size:
img = resize(img,out_size)
if mask.shape[0] != h:
mask = cv2.resize(mask,(w,h))
img_mosaic = img.copy()
if model=='squa_avg':
for i in range(h_step):
for j in range(w_step):
if mask[i*n+pix_mid_h,j*n+pix_mid_w]:
img_mosaic[i*n+h_start:(i+1)*n+h_start,j*n+w_start:(j+1)*n+w_start,:]=\
img[i*n+h_start:(i+1)*n+h_start,j*n+w_start:(j+1)*n+w_start,:].mean(axis=(0,1))
elif model=='squa_mid':
for i in range(h_step):
for j in range(w_step):
if mask[i*n+pix_mid_h,j*n+pix_mid_w]:
img_mosaic[i*n+h_start:(i+1)*n+h_start,j*n+w_start:(j+1)*n+w_start,:]=\
img[i*n+n//2+h_start,j*n+n//2+w_start,:]
elif model == 'squa_random':
for i in range(h_step):
for j in range(w_step):
if mask[i*n+pix_mid_h,j*n+pix_mid_w]:
img_mosaic[i*n+h_start:(i+1)*n+h_start,j*n+w_start:(j+1)*n+w_start,:]=\
img[h_start+int(i*n-n/2+n*random.random()),w_start+int(j*n-n/2+n*random.random()),:]
elif model == 'squa_avg_circle_edge':
for i in range(h_step):
for j in range(w_step):
img_mosaic[i*n+h_start:(i+1)*n+h_start,j*n+w_start:(j+1)*n+w_start,:]=\
img[i*n+h_start:(i+1)*n+h_start,j*n+w_start:(j+1)*n+w_start,:].mean(axis=(0,1))
mask = cv2.threshold(mask,127,255,cv2.THRESH_BINARY)[1]
_mask = ch_one2three(mask)
mask_inv = cv2.bitwise_not(_mask)
imgroi1 = cv2.bitwise_and(_mask,img_mosaic)
imgroi2 = cv2.bitwise_and(mask_inv,img)
img_mosaic = cv2.add(imgroi1,imgroi2)
elif model =='rect_avg':
n_h = n
n_w = int(n*rect_rat)
n_h_half = n_h//2+h_start
n_w_half = n_w//2+w_start
for i in range((h-h_start)//n_h):
for j in range((w-w_start)//n_w):
if mask[i*n_h+n_h_half,j*n_w+n_w_half]:
img_mosaic[i*n_h+h_start:(i+1)*n_h+h_start,j*n_w+w_start:(j+1)*n_w+w_start,:]=\
img[i*n_h+h_start:(i+1)*n_h+h_start,j*n_w+w_start:(j+1)*n_w+w_start,:].mean(axis=(0,1))
if feather != -1:
if feather==0:
mask = (cv2.blur(mask, (n, n)))
else:
mask = (cv2.blur(mask, (feather, feather)))
mask = mask/255.0
for i in range(3):img_mosaic[:,:,i] = (img[:,:,i]*(1-mask)+img_mosaic[:,:,i]*mask)
img_mosaic = img_mosaic.astype(np.uint8)
return img_mosaic
def get_autosize(img,mask,area_type = 'normal'):
h,w = img.shape[:2]
size = np.min([h,w])
mask = resize(mask,size)
alpha = size/512
try:
if area_type == 'normal':
area = mask_area(mask)
elif area_type == 'bounding':
w,h = cv2.boundingRect(mask)[2:]
area = w*h
except:
area = 0
area = area/(alpha*alpha)
if area>50000:
size = alpha*((area-50000)/50000+12)
elif 20000<area<=50000:
size = alpha*((area-20000)/30000+8)
elif 5000<area<=20000:
size = alpha*((area-5000)/20000+7)
elif 0<=area<=5000:
size = alpha*((area-0)/5000+6)
else:
pass
return size
def get_random_parameter(img,mask):
# mosaic size
p = np.array([0.5,0.5])
mod = np.random.choice(['normal','bounding'], p = p.ravel())
mosaic_size = get_autosize(img,mask,area_type = mod)
mosaic_size = int(mosaic_size*random.uniform(0.9,2.5))
# mosaic mod
p = np.array([0.25, 0.3, 0.45])
mod = np.random.choice(['squa_mid','squa_avg','rect_avg'], p = p.ravel())
# rect_rat for rect_avg
rect_rat = random.uniform(1.1,1.6)
# feather size
feather = -1
if random.random()<0.7:
feather = int(mosaic_size*random.uniform(0,1.5))
return mosaic_size,mod,rect_rat,feather
def addmosaic_autosize(img,mask,model,area_type = 'normal'):
mosaic_size = get_autosize(img,mask,area_type = 'normal')
img_mosaic = addmosaic_base(img,mask,mosaic_size,model = model)
return img_mosaic
def addmosaic_random(img,mask):
mosaic_size,mod,rect_rat,feather = get_random_parameter(img,mask)
img_mosaic = addmosaic_base(img,mask,mosaic_size,model = mod,rect_rat=rect_rat,feather=feather)
return img_mosaic
def get_random_startpos(num,bisa_p,bisa_max,bisa_max_part):
pos = np.zeros((num,2), dtype=np.int64)
if random.random()<bisa_p:
indexs = random.sample((np.linspace(1,num-1,num-1,dtype=np.int64)).tolist(), random.randint(1, bisa_max_part))
indexs.append(0)
indexs.append(num)
indexs.sort()
for i in range(len(indexs)-1):
pos[indexs[i]:indexs[i+1]] = [random.randint(0,bisa_max),random.randint(0,bisa_max)]
return pos
@@ -0,0 +1,147 @@
import json
import os
import random
import string
import shutil
def Traversal(filedir):
file_list=[]
for root,dirs,files in os.walk(filedir):
for file in files:
file_list.append(os.path.join(root,file))
for dir in dirs:
Traversal(dir)
return file_list
def randomstr(num):
return ''.join(random.sample(string.ascii_letters + string.digits, num))
def is_img(path):
ext = os.path.splitext(path)[1]
ext = ext.lower()
if ext in ['.jpg','.png','.jpeg','.bmp']:
return True
else:
return False
def is_video(path):
ext = os.path.splitext(path)[1]
ext = ext.lower()
if ext in ['.mp4','.flv','.avi','.mov','.mkv','.wmv','.rmvb','.mts']:
return True
else:
return False
def is_imgs(paths):
tmp = []
for path in paths:
if is_img(path):
tmp.append(path)
return tmp
def is_videos(paths):
tmp = []
for path in paths:
if is_video(path):
tmp.append(path)
return tmp
def is_dirs(paths):
tmp = []
for path in paths:
if os.path.isdir(path):
tmp.append(path)
return tmp
def writelog(path,log,isprint=False):
f = open(path,'a+')
f.write(log+'\n')
f.close()
if isprint:
print(log)
def savejson(path,data_dict):
json_str = json.dumps(data_dict)
f = open(path,'w+')
f.write(json_str)
f.close()
def loadjson(path):
f = open(path, 'r')
txt_data = f.read()
f.close()
return json.loads(txt_data)
def makedirs(path):
if os.path.isdir(path):
print(path,'existed')
else:
os.makedirs(path)
print('makedir:',path)
def clean_tempfiles(opt,tmp_init=True):
tmpdir = opt.temp_dir
if os.path.isdir(tmpdir):
print('Clean temp...')
shutil.rmtree(tmpdir)
if tmp_init:
os.makedirs(tmpdir)
os.makedirs(os.path.join(tmpdir, 'video2image'))
os.makedirs(os.path.join(tmpdir, 'addmosaic_image'))
os.makedirs(os.path.join(tmpdir, 'replace_mosaic'))
os.makedirs(os.path.join(tmpdir, 'mosaic_mask'))
os.makedirs(os.path.join(tmpdir, 'ROI_mask'))
os.makedirs(os.path.join(tmpdir, 'style_transfer'))
# make dataset
os.makedirs(os.path.join(tmpdir, 'mosaic_crop'))
os.makedirs(os.path.join(tmpdir, 'ROI_mask_check'))
def file_init(opt):
if not os.path.isdir(opt.result_dir):
os.makedirs(opt.result_dir)
print('makedir:',opt.result_dir)
clean_tempfiles(opt,True)
def second2stamp(s):
h = int(s/3600)
s = int(s%3600)
m = int(s/60)
s = int(s%60)
return "%02d:%02d:%02d" % (h, m, s)
def stamp2second(stamp):
substamps = stamp.split(':')
return int(substamps[0])*3600 + int(substamps[1])*60 + int(substamps[2])
def counttime(start_time,current_time,now_num,all_num):
'''
start_time,current_time: time.time()
'''
used_time = int(current_time-start_time)
all_time = int(used_time/now_num*all_num)
return second2stamp(used_time)+'/'+second2stamp(all_time)
def get_bar(percent,num = 25):
bar = '['
for i in range(num):
if i < round(percent/(100/num)):
bar += '#'
else:
bar += '-'
bar += ']'
return bar+' '+"%.2f"%percent+'%'
def copyfile(src,dst):
try:
shutil.copyfile(src, dst)
except Exception as e:
print(e)
def opt2str(opt):
message = ''
message += '---------------------- Options --------------------\n'
for k, v in sorted(vars(opt).items()):
message += '{:>25}: {:<35}\n'.format(str(k), str(v))
message += '----------------- End -------------------'
return message
+20 -2
View File
@@ -9,11 +9,20 @@ DeepMosaics / LADA later) plug in behind the same interface.
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Callable
import numpy as np
from ..detection.types import Detection
# Optional cooperative-cancel hook: returns True to abort. Engines that loop or
# drive a subprocess should poll it; instant engines may ignore it.
CancelCheck = Callable[[], bool]
class Cancelled(Exception):
"""Raised by a Restorer when ``should_cancel`` asked it to stop."""
class Restorer(ABC):
@property
@@ -21,6 +30,15 @@ class Restorer(ABC):
return type(self).__name__
@abstractmethod
def restore(self, image: np.ndarray, detections: list[Detection]) -> np.ndarray:
"""Return a copy of ``image`` with the detected regions reconstructed."""
def restore(
self,
image: np.ndarray,
detections: list[Detection],
should_cancel: CancelCheck | None = None,
) -> np.ndarray:
"""Return a copy of ``image`` with the detected regions reconstructed.
``should_cancel`` (if given) is polled periodically; when it returns
True the engine should abort and raise :class:`Cancelled`.
"""
raise NotImplementedError
+128 -74
View File
@@ -1,107 +1,161 @@
"""DeepMosaics restorer — real generative mosaic removal.
"""DeepMosaics restorer — real generative mosaic removal, in-process.
Rather than vendoring DeepMosaics' GPL network code (which must match the exact
checkpoint), we drive a **user-installed** DeepMosaics (https://github.com/HypoX64/DeepMosaics)
as a subprocess: write the frame to a temp file, run ``deepmosaic.py --mode clean``,
read the cleaned image back. This reuses their tested pipeline (incl. their own
mosaic locator ``mosaic_position.pth``) and respects the GPL boundary.
The DeepMosaics network code (GPL-3.0) is vendored under ``_deepmosaics/`` (see
its NOTICE/LICENSE). We load the models **once** and run the per-frame clean path
in-process — far faster than spawning a subprocess per frame (which reloaded the
models every time). Only the model *weights* are user-supplied.
Setup the user must do once (see README → Восстановление):
1. ``git clone https://github.com/HypoX64/DeepMosaics`` and install its deps.
2. Download clean weights (e.g. ``clean_youknow_video.pth``) AND ``mosaic_position.pth``
into one folder.
3. In the app: Восстановление… → engine "deepmosaics", set the DeepMosaics folder
and the clean-model path (a CUDA GPU is strongly recommended).
Per-frame clean = DeepMosaics' ``cleanmosaic_img_server`` logic, reimplemented
here (so we don't pull in their video/ffmpeg modules):
locate mosaic (BiSeNet ``mosaic_position.pth``) → run the clean generator on the
crop → feather it back. DeepMosaics finds the mosaic itself; our detections are
used for navigation, not passed to it.
NOTE: DeepMosaics finds the mosaic itself; our detections are used for navigation,
not passed to it.
Setup (see README → Восстановление): download the **image** clean weights
``clean_youknow_resnet_9blocks.pth`` + ``mosaic_position.pth`` into one folder and
point the app at the clean-model file. The video model ``clean_youknow_video.pth``
(BVDNet) needs neighbour frames and does NOT work per-frame.
"""
from __future__ import annotations
import subprocess
import sys
import tempfile
from pathlib import Path
from types import SimpleNamespace
import numpy as np
from ..detection.types import Detection
from ..imageio import imread_unicode, imwrite_unicode
from .base import Restorer
from .base import CancelCheck, Cancelled, Restorer
_IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp"}
_VENDOR = Path(__file__).parent / "_deepmosaics"
# Default place to drop DeepMosaics clean weights (gitignored — see models/).
DEFAULT_WEIGHTS_DIR = Path(__file__).resolve().parents[3] / "models" / "deepmosaics"
def discover_models(extra_dir: str | None = None) -> list[tuple[str, str]]:
"""Find usable per-frame clean models: (display_name, full_path).
Scans the bundled ``models/deepmosaics`` folder (plus ``extra_dir`` if given)
for ``clean_*.pth``. The video model is skipped — it can't run per-frame.
"""
dirs = [DEFAULT_WEIGHTS_DIR]
if extra_dir:
dirs.insert(0, Path(extra_dir))
out: list[tuple[str, str]] = []
seen: set[str] = set()
for d in dirs:
if not d.is_dir():
continue
for p in sorted(d.glob("clean_*.pth")):
if "video" in p.name.lower() or p.name in seen:
continue
seen.add(p.name)
out.append((p.stem, str(p)))
return out
def _netg_kind(model_name: str) -> str:
"""Pick DeepMosaics' netG type from the weights filename (see their options.py)."""
n = model_name.lower()
if "video" in n:
raise ValueError(
"Видеомодель (clean_*_video.pth) не работает покадрово — ей нужен соседний "
"кадр.\nУкажите картиночную модель clean_youknow_resnet_9blocks.pth."
)
if "unet_128" in n:
return "unet_128"
if "hd" in n:
return "HD"
return "resnet_9blocks"
class DeepMosaicsRestorer(Restorer):
def __init__(
self,
deepmosaics_dir: str | None,
deepmosaics_dir: str | None, # kept for factory/config compatibility (weights hint)
model_path: str | None,
python_exe: str | None = None,
python_exe: str | None = None, # unused now (in-process)
gpu_id: str = "0",
) -> None:
if not deepmosaics_dir or not (Path(deepmosaics_dir) / "deepmosaic.py").is_file():
raise ValueError(
"Не указана папка DeepMosaics (с deepmosaic.py).\n"
"Установите DeepMosaics и укажите её в «Восстановление…». См. README."
)
if not model_path or not Path(model_path).is_file():
discovered = discover_models() # fall back to a bundled model
if discovered:
model_path = discovered[0][1]
else:
raise ValueError(
"Не найдены веса DeepMosaics (clean_*.pth).\n"
"Положите clean_youknow_resnet_9blocks.pth + mosaic_position.pth в "
"models/deepmosaics (или выберите в «Восстановление…»). См. README."
)
model = Path(model_path)
self._netg = _netg_kind(model.name) # raises on a video model
pos = self._find_mosaic_position(model, deepmosaics_dir)
if pos is None:
raise ValueError(
"Не найдены веса DeepMosaics (clean_*.pth).\n"
"Скачайте clean_youknow_video.pth + mosaic_position.pth в одну папку. См. README."
"Рядом с clean-моделью не найден mosaic_position.pth.\n"
"Положите mosaic_position.pth в ту же папку, что и clean_*.pth. См. README."
)
self._dir = Path(deepmosaics_dir)
self._model = model_path
self._python = python_exe or sys.executable
self._model = str(model)
self._pos = str(pos)
self._gpu = gpu_id
self._loaded = False # models loaded lazily on first restore
@staticmethod
def _find_mosaic_position(model: Path, dm_dir: str | None) -> Path | None:
candidates = [model.parent / "mosaic_position.pth"]
if dm_dir:
candidates.append(Path(dm_dir) / "pretrained_models" / "mosaic" / "mosaic_position.pth")
return next((p for p in candidates if p.is_file()), None)
@property
def name(self) -> str:
return f"DeepMosaics(gpu={self._gpu})"
def restore(self, image: np.ndarray, detections: list[Detection]) -> np.ndarray:
with tempfile.TemporaryDirectory(prefix="hvt_dm_") as tmp:
tmpd = Path(tmp)
src = tmpd / "frame.jpg"
result_dir = tmpd / "result"
result_dir.mkdir()
imwrite_unicode(str(src), image)
# ------------------------------------------------------------------ engine
def _ensure_loaded(self) -> None:
if self._loaded:
return
if str(_VENDOR) not in sys.path:
sys.path.insert(0, str(_VENDOR)) # so vendored `from models/util import …` resolve
from models import loadmodel, runmodel # type: ignore # noqa: E402
import util.image_processing as impro # type: ignore # noqa: E402
cmd = [
self._python, "deepmosaic.py",
"--media_path", str(src),
"--model_path", str(self._model),
"--mode", "clean",
"--result_dir", str(result_dir),
"--temp_dir", str(tmpd / "dmtmp"),
"--gpu_id", str(self._gpu),
"--no_preview",
]
proc = subprocess.run(
cmd, cwd=str(self._dir),
stdin=subprocess.DEVNULL, # so DeepMosaics' error input() can't hang
capture_output=True, text=True,
)
outputs = [p for p in result_dir.iterdir() if p.suffix.lower() in _IMG_EXTS]
if outputs:
newest = max(outputs, key=lambda p: p.stat().st_mtime)
restored = imread_unicode(str(newest))
if restored is None:
raise RuntimeError("Не удалось прочитать результат DeepMosaics.")
return restored
self._runmodel = runmodel
self._impro = impro
self._opt = SimpleNamespace(
gpu_id=self._gpu,
netG=self._netg,
model_path=self._model,
mosaic_position_model_path=self._pos,
mask_threshold=64,
all_mosaic_area=False,
ex_mult=1.5,
no_feather=False,
traditional=False,
)
self._netM = loadmodel.bisenet(self._opt, "mosaic")
self._netG = loadmodel.pix2pix(self._opt)
self._loaded = True
# No output file — figure out why.
log = (proc.stderr or "") + (proc.stdout or "")
if "BVDNet.forward()" in log or "argument: 'previous'" in log:
raise RuntimeError(
"Видеомодель (clean_*_video.pth) не работает покадрово — ей нужен "
"соседний кадр.\nУкажите картиночную модель clean_youknow_resnet_9blocks.pth."
)
if proc.returncode == 0:
# DeepMosaics ran fine but found no mosaic to clean — keep the frame as is.
return image.copy()
tail = log.strip().splitlines()[-6:]
raise RuntimeError(
f"DeepMosaics не вернул результат (код {proc.returncode}).\n" + "\n".join(tail)
)
def restore(
self,
image: np.ndarray,
detections: list[Detection],
should_cancel: CancelCheck | None = None,
) -> np.ndarray:
if should_cancel is not None and should_cancel():
raise Cancelled("Восстановление отменено")
self._ensure_loaded()
rm, impro, opt = self._runmodel, self._impro, self._opt
# DeepMosaics' cleanmosaic_img_server, faithfully reproduced.
x, y, size, mask = rm.get_mosaic_position(image, self._netM, opt)
if size <= 100:
return image.copy() # no mosaic located — leave the frame untouched
if should_cancel is not None and should_cancel():
raise Cancelled("Восстановление отменено")
work = image.copy()
img_mosaic = work[y - size:y + size, x - size:x + size]
img_fake = rm.run_pix2pix(img_mosaic, self._netG, opt)
return impro.replace_mosaic(work, img_fake, mask, x, y, size, opt.no_feather)
+3 -2
View File
@@ -1,8 +1,9 @@
"""Restorer factory: build a Restorer from the app config.
- ``inpaint``: cv2 baseline (no weights, no GPU; fills, doesn't reconstruct).
- ``deepmosaics``: real generative mosaic removal via a user-installed DeepMosaics
(subprocess). Needs the DeepMosaics folder + clean weights + (ideally) a CUDA GPU.
- ``deepmosaics``: real generative mosaic removal. The DeepMosaics network code is
vendored (``_deepmosaics/``, GPL-3.0) and run in-process; the user supplies only the
clean weights (+ ``mosaic_position.pth`` alongside). A CUDA GPU is recommended.
"""
from __future__ import annotations
+8 -2
View File
@@ -13,7 +13,7 @@ import cv2
import numpy as np
from ..detection.types import Detection
from .base import Restorer
from .base import CancelCheck, Restorer
from .mask import detections_to_mask
@@ -27,7 +27,13 @@ class InpaintRestorer(Restorer):
def name(self) -> str:
return f"InpaintRestorer({self.method})"
def restore(self, image: np.ndarray, detections: list[Detection]) -> np.ndarray:
def restore(
self,
image: np.ndarray,
detections: list[Detection],
should_cancel: CancelCheck | None = None,
) -> np.ndarray:
# Single cv2.inpaint call — effectively instant, so cancellation is moot.
if not detections:
return image.copy()
mask = detections_to_mask(image.shape, detections, dilate=self.dilate)