Merge branch 'main' into Feature_Extractor

This commit is contained in:
Sven Vogel 2023-06-18 10:32:06 +02:00
commit 805397a6e1
23 changed files with 1406 additions and 35 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@
.DS_Store .DS_Store
.idea .idea
/.vscode /.vscode
*.json

339
LICENSE Normal file
View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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.

View File

@ -1,12 +1,82 @@
# Programmentwurf # Imsearch
Die Beschreibung der Aufgabenstellung ist unter [Programmentwurf.md](https://github.com/programmieren-mit-rust/programmentwurf/blob/main/Programmentwurf.md) zu finden. Diese `Readme.md` ist durch etwas Sinnvolles zu ersetzen. Extensible library for creating an image based search engine. The library exposes the functionality to create databases which index various images stored as png files.
# WICHTIG! Files can be compared for similarity by either premade features or custom ones. The basic idea of handling the library is as follows:
Kleiner reminder, wenn ihr Sachen pushed in das repo, die eurer Anischt nach fertig sind (z.B für einen Pull-Request!), bitte mit den folgenden Commands auf Fehler/Warnings überprüfen:
- `cargo fmt` für formattierung - Create a new database
- `cargo clippy` für warnings - Add some features to the database
- `cargo test doc` für documentation tests - Add some images to the database
optional: - Search for some images in the database by a certain feature
- `cargo test` für module tests - Save the database to disk
- `cargo bench` für benchmarks
or:
- Load a database form disk
- Supply generator functions
- Search for some images in the database by a certain feature
- Add some images to the database
- Save the database to disk
# Examples:
## Define a new feature
```rust
/// Compute the average value of the tree color channels of a given image
fn average_rgb_value(image: Arc<Image<f32>>) -> (String, FeatureResult) {
let bright = image
.pixels()
.iter()
.map(|(r, g, b, _)| (r + g + b) / 3.0 / 255.0)
.sum::<f32>();
(
String::from("average_brightness"),
FeatureResult::Percent(bright / image.pixels().len() as f32),
)
}
```
## Create a new database
```rust
let files: Vec<PathBuf> = std::fs::read_dir("image/folder/")
.unwrap()
.map(|f| f.unwrap().path())
.collect();
let feats: Vec<FeatureGenerator> = vec![average_rgb_value];
let db = Database::new(&files, feats).unwrap();
db.write_to_file(json);
```
## Read a new database and search for similar images
```rust
let db = Database::from_file(Path::new("db.json"));
for results in db
.search(
std::path::Path::new("path/to/image.png"),
average_brightness,
)
.unwrap()
{
println!(
"path: {} similarity: {}",
results.0.as_os_str().to_str().unwrap(),
results.1
);
}
```
# Details
Processing of features for images are multithreaded. Features that are calculated for images only get their results stored. The generator function used to calculate won't get serialized. This implies that
in order to compute the features for images the generator functions have to be passed to the database
after it has been read from a file.
## Limiting thread usage
You can limit the number of threads to be used by calling `set_limit()` on the database.
Note that the thread pool will automatically try to detect the optimal number of threads to use.
As long as no edge case such as running in an over committed virtual machine applies this will be
good enough for most cases.
## Image formats
The library can only handle png files through the `png` crate. Note that not all colortypes are supported. Due to the poor capabilites of the crate pngs with indexed palettes are not functional
will cause functions to return error values.
## Memory usage
The database won't hold all images in ram at the same time. They are loaded on demand when calculating features for them. This may cause increased disk usage but will prevent ram overcommitment.

View File

@ -45,12 +45,15 @@ fn dot_parallel(a: Arc<Vec<f64>>, b: Arc<Vec<f64>>, threads: usize) {
for i in 0..threads { for i in 0..threads {
// offset of the first element for the thread local vec // offset of the first element for the thread local vec
let chunk = i * steps; let chunk = i * steps;
// create a new strong reference to the vector
let aa = a.clone();
let bb = b.clone();
// launch a new thread // launch a new thread
pool.enqueue(Task::new( pool.enqueue(Task::new(
(chunk, steps, a.clone(), b.clone()), (aa, bb, chunk, steps),
|(block, inc, a, b)| { |(aa, bb, chunk, steps)| {
let a = &a[block..(block + inc)]; let a = &aa[chunk..(chunk + steps)];
let b = &b[block..(block + inc)]; let b = &bb[chunk..(chunk + steps)];
dot(a, b) dot(a, b)
}, },
)); ));
@ -115,12 +118,15 @@ fn pool_overusage(a: Arc<Vec<f64>>, b: Arc<Vec<f64>>, threads: usize) {
for i in 0..threads { for i in 0..threads {
// offset of the first element for the thread local vec // offset of the first element for the thread local vec
let chunk = i * steps; let chunk = i * steps;
// create a new strong reference to the vector
let aa = a.clone();
let bb = b.clone();
// launch a new thread // launch a new thread
pool.enqueue(Task::new( pool.enqueue(Task::new(
(chunk, steps, a.clone(), b.clone()), (aa, bb, chunk, steps),
|(block, inc, a, b)| { |(aa, bb, chunk, steps)| {
let a = &a[block..(block + inc)]; let a = &aa[chunk..(chunk + steps)];
let b = &b[block..(block + inc)]; let b = &bb[chunk..(chunk + steps)];
dot(a, b) dot(a, b)
}, },
)); ));

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

BIN
res/integration/hut.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 539 B

BIN
res/integration/rot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 B

BIN
res/test_img/gray_image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

BIN
res/test_img/hut.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 711 B

BIN
res/test_img/red_image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 539 B

BIN
res/test_img/rot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 B

BIN
res/test_img/town_blue.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

BIN
res/test_img/wrong size.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

@ -40,7 +40,7 @@ pub trait Sample: Into<f32> + PartialEq + Default + Copy + From<u8> + PartialOrd
impl<T: Into<f32> + PartialEq + Default + Copy + From<u8> + PartialOrd> Sample for T {} impl<T: Into<f32> + PartialEq + Default + Copy + From<u8> + PartialOrd> Sample for T {}
#[allow(unused)] #[allow(unused)]
#[derive(Default)] #[derive(Default, Debug)]
pub struct Image<T> pub struct Image<T>
where where
T: Sample, T: Sample,
@ -87,6 +87,10 @@ where
pub fn pixel(&self, index: usize) -> (T, T, T, T) { pub fn pixel(&self, index: usize) -> (T, T, T, T) {
*self.index(index) *self.index(index)
} }
/// Returns all pixel of the image
pub fn pixels(&self) -> &Vec<(T, T, T, T)> {
&self.pixels
}
/// Returns the path of the image /// Returns the path of the image
pub fn path(&self) -> &PathBuf { pub fn path(&self) -> &PathBuf {
&self.path &self.path

333
src/image_loader/mod.rs Normal file
View File

@ -0,0 +1,333 @@
use crate::image::Image;
use png::BitDepth;
use std::fs::File;
use std::path::Path;
///# Image Loader
/// The image_loader function is a function which can use a path of an image to return some Metadata from the image.<br>
///It can also retrieve the rgba values of every pixel from the image and the path.<br>
///<br>
///# IMPORTANT<br>
/// Doesn't support pictures with the color type indexed!<br>
///<br>
///# Parameter
///The function has the parameter path with the type &Path.<br>
///<br>
///# Return variables
///The return value is a struct which includes four variables.<br>
///1. width [u32]: width contains the number of pixels in a row of the given png.<br>
///2. height [u32]: height contains the height of the picture in measured pixels.<br>
///3. pixel_vec [Vec<(f32, f32, f32, f32)>]: pixel_vec contains the rgba values of every pixel in the picture, saved in a vec themselves.<br>
///4. path [path.to_path_buf()]: is the path from the parameter.<br>
pub fn image_loader(path: &Path) -> Result<Image<f32>, &'static str> {
let decoder = match File::open(path) {
Ok(file) => png::Decoder::new(file),
Err(_) => return Err("failed the decoder"),
};
let mut reader = match decoder.read_info() {
Ok(reader) => reader,
Err(_) => return Err("Failed to read PNG info"),
};
let mut buf = vec![0; reader.output_buffer_size()];
let info = match reader.next_frame(&mut buf) {
Ok(info) => info,
Err(_) => return Err("Failed to read PNG frame"),
};
let bit_depth = reader.info().bit_depth;
let color_type = reader.info().color_type;
let width = reader.info().width;
let height = reader.info().height;
let idat = &buf[..info.buffer_size()];
let pixel_vec = match color_type {
png::ColorType::Grayscale => grayscale_to_rgba(idat, bit_depth),
png::ColorType::GrayscaleAlpha => grayscale_alpha_to_rgba(idat, bit_depth),
png::ColorType::Rgb => rgb_to_rgba(idat, bit_depth),
png::ColorType::Rgba => decode_rgba(idat, bit_depth),
_ => panic!("Unsupported color type or bit depth"),
}?;
let image: Image<f32> = Image::new(width, height, pixel_vec, path.to_path_buf());
Ok(image)
}
///# Grayscale to RGBA
///The grayscale_to_rgba function converts a IDAT chunk from an picture with the color type grayscale and the bit depth into an RGBA value.<br>
/// <br>
///# Parameter
///The function has the following two parameters:<br>
///1. IDAT [&[u8]]: This array cointans the IDAT chunk of the given image.<br>
///2. bit_depth [BitDepth]: This variable contains the bit depth of the given image.<br>
///<br>
///# Return variables
///This function returns a vector filled with vectors filled with four [f32] variables, which are the RGBA values.<br>
///Also this function sets the alpha channel of the RGBA value to 255.
fn grayscale_to_rgba(
idat: &[u8],
bit_depth: BitDepth,
) -> Result<Vec<(f32, f32, f32, f32)>, &'static str> {
let mut rgba_values = Vec::new();
let max_value: u32 = (1 << bit_depth as u32) - 1;
for byte in idat {
let grayscale = match bit_depth {
BitDepth::One => ((*byte & 0x01) as u32 * max_value) as f32,
BitDepth::Two => ((*byte & 0x03) as u32 * max_value / 3) as f32,
BitDepth::Four => ((*byte & 0x0F) as u32 * max_value / 15) as f32,
BitDepth::Eight => *byte as f32,
BitDepth::Sixteen => ((*byte as u32 * 255) / max_value) as f32,
};
let rgba = (grayscale, grayscale, grayscale, 255_f32);
rgba_values.push(rgba);
}
Ok(rgba_values)
}
///# Grayscale Alpha to RGBA
///The grayscale_alpha_to_rgba function converts a IDAT chunk from a picture with the color type grayscale alpha and the bit depth into an RGBA value.<br>
/// <br>
///# Parameter
///The function has the following two parameters:<br>
///1. IDAT [&[u8]]: This array contains the IDAT chunk of the given image.<br>
///2. bit_depth [BitDepth]: This variable contains the bit depth of the given image.<br>
///<br>
///# Return variables
///This function returns a vector filled with vectors filled with four [f32] variables, which are the RGBA values.
fn grayscale_alpha_to_rgba(
idat: &[u8],
bit_depth: BitDepth,
) -> Result<Vec<(f32, f32, f32, f32)>, &'static str> {
let mut rgba_values = Vec::new();
let chunk_size;
if bit_depth == BitDepth::Eight {
chunk_size = 2;
} else if bit_depth == BitDepth::Sixteen {
chunk_size = 4;
} else {
return Err("Invalid Bit Depth");
}
for pair in idat.chunks(chunk_size) {
if pair.len() < 2 {
return Err("Insufficient data");
}
let grayscale = match bit_depth {
BitDepth::Eight => pair[0] as f32,
BitDepth::Sixteen => ((pair[0] as u16) << 8 | pair[1] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let alpha = match bit_depth {
BitDepth::Eight => pair[1] as f32,
BitDepth::Sixteen => ((pair[2] as u16) << 8 | pair[3] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let rgba = (grayscale, grayscale, grayscale, alpha);
rgba_values.push(rgba);
}
Ok(rgba_values)
}
///# RGB to RGBA
///The tgb_to_rgba function converts a IDAT chunk from a picture with the color type rgb and the bit depth into an RGBA value.<br>
/// <br>
///# Parameter
///The function has the following two parameters:<br>
///1. IDAT [&[u8]]: This array contains the IDAT chunk of the given image.<br>
///2. bit_depth [BitDepth]: This variable contains the bit depth of the given image.<br>
///<br>
///# Return variables
///This function returns a vector filled with vectors filled with four [f32] variables, which are the RGBA values.
///Also this function sets the alpha channel of the RGBA value to 255.
fn rgb_to_rgba(
idat: &[u8],
bit_depth: BitDepth,
) -> Result<Vec<(f32, f32, f32, f32)>, &'static str> {
let mut rgba_values = Vec::new();
let chunk_size;
if bit_depth == BitDepth::Eight {
chunk_size = 3;
} else if bit_depth == BitDepth::Sixteen {
chunk_size = 6;
} else {
return Err("Invalid Bit Depth");
}
for group in idat.chunks(chunk_size) {
if group.len() < 3 {
return Err("Insufficient data");
}
let red = match bit_depth {
BitDepth::Eight => group[0] as f32,
BitDepth::Sixteen => ((group[0] as u16) << 8 | group[1] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let green = match bit_depth {
BitDepth::Eight => group[1] as f32,
BitDepth::Sixteen => ((group[2] as u16) << 8 | group[3] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let blue = match bit_depth {
BitDepth::Eight => group[2] as f32,
BitDepth::Sixteen => ((group[4] as u16) << 8 | group[5] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let rgba = (red, green, blue, 255_f32);
rgba_values.push(rgba);
}
Ok(rgba_values)
}
///# Decode RGBA
///The decode_rgba function converts a IDAT chunk from a picture with the color type rgba and the bit depth into an RGBA value.<br>
/// <br>
///# Parameter
///The function has the following two parameters:<br>
///1. IDAT [&[u8]]: This array contains the IDAT chunk of the given image.<br>
///2. bit_depth [BitDepth]: This variable contains the bit depth of the given image.<br>
///<br>
///# Return variables
///This function returns a vector filled with vectors filled with four [f32] variables, which are the RGBA values.
fn decode_rgba(
idat: &[u8],
bit_depth: BitDepth,
) -> Result<Vec<(f32, f32, f32, f32)>, &'static str> {
let mut rgba_values = Vec::new();
let chunk_size;
if bit_depth == BitDepth::Eight {
chunk_size = 4;
} else if bit_depth == BitDepth::Sixteen {
chunk_size = 8;
} else {
return Err("Invalid Bit Depth");
}
for group in idat.chunks(chunk_size) {
if group.len() < 4 {
return Err("Insufficient data");
}
let red = match bit_depth {
BitDepth::Eight => group[0] as f32,
BitDepth::Sixteen => ((group[0] as u16) << 8 | group[1] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let green = match bit_depth {
BitDepth::Eight => group[1] as f32,
BitDepth::Sixteen => ((group[2] as u16) << 8 | group[3] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let blue = match bit_depth {
BitDepth::Eight => group[2] as f32,
BitDepth::Sixteen => ((group[4] as u16) << 8 | group[5] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let alpha = match bit_depth {
BitDepth::Eight => group[3] as f32,
BitDepth::Sixteen => ((group[6] as u16) << 8 | group[7] as u16) as f32,
_ => return Err("Unsupported bit depth"),
};
let rgba = (red, green, blue, alpha);
rgba_values.push(rgba);
}
Ok(rgba_values)
}
#[cfg(test)]
mod test {
use std::path::PathBuf;
use super::*;
#[test]
fn test_image_loader() {
let path = Path::new("res/test_img/red_image.png");
let test = image_loader(path);
let image = Image::new(
4,
4,
vec![
(255., 0., 0., 255.),
(0., 255., 0., 255.),
(0., 0., 255., 255.),
(255., 255., 255., 255.),
(127., 127., 127., 255.),
(0., 255., 255., 255.),
(255., 255., 0., 255.),
(255., 0., 0., 255.),
(127., 127., 127., 255.),
(255., 0., 255., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(0., 0., 0., 255.),
],
PathBuf::default(),
);
assert_eq!(test.unwrap().pixels(), image.pixels())
}
#[test]
#[should_panic]
fn test_wrong_img() {
let path = Path::new("res/test_img/wrong pixel count.png");
let test = image_loader(path);
let image = Image::new(
4,
4,
vec![
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
(255., 0., 0., 255.),
],
PathBuf::default(),
);
//should panic because we are looking at a corrupt picture
assert_eq!(test.unwrap().pixels(), image.pixels())
}
}

View File

@ -1,19 +1,6 @@
extern crate core; extern crate core;
pub mod image; pub mod image;
pub mod image_loader;
pub mod multithreading; pub mod multithreading;
pub mod search_index;
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}

View File

@ -174,6 +174,13 @@ where
} }
} }
/// Set a new limit to the amount of used threads.
/// This will only take effect when new threads are created. Currently running threads
/// will continue to do so.
pub fn set_limt(&mut self, limit: NonZeroUsize) {
self.limit = limit;
}
/// Put a new job into the queue to be executed by a thread in the future. /// Put a new job into the queue to be executed by a thread in the future.
/// The priority of the job will determine if the job will be put at the start or end of the queue. /// The priority of the job will determine if the job will be put at the start or end of the queue.
/// See [`crate::multithreading::Priority`]. /// See [`crate::multithreading::Priority`].

542
src/search_index/mod.rs Normal file
View File

@ -0,0 +1,542 @@
//!
//! This module provides the Database for Images and compare methods to search in it.
//!
//! The database Struct provides the Images and has a threadpool to efficiently process all given features for all Images
//!
//!
//! to generate a database you need a vector of paths of picture that you want to save and search in it.
//! You also need a Vector of Feature generator functions that generates the feature of every image
//!
//!
//!```rust ignore
//! # use std::path::{Path, PathBuf};
//! # use imsearch::image::Image;
//! # use imsearch::search_index;
//! use imsearch::search_index::FeatureGenerator;
//!
//! let path: Vec<PathBuf> = Vec::new();
//! let features: Vec<FeatureGenerator> = Vec::new();
//!
//! let mut database = search_index::Database::new(&path, features).unwrap();
//! database.add_image(Path::new("testpath")).unwrap();
//! ```
//!
//!
//!This Library provides some Feature generator functions but you can also create your own.
//!The Feature generator has to fit in the "FeatureGenerator" type to work with the database.
//!
//!
use crate::image::Image;
use crate::multithreading::{Task, ThreadPool};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::default::Default;
use std::fs;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
///this trait provides a function to compare objects and returns a f32 between 0 and 1.
/// 1 is identical and 0 is different. with this trait you get the similarity between the objects
trait WeightedCmp {
fn weighted(&self, other: &Self) -> f32;
}
/// Every feature returns a known and sized type from this enum
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FeatureResult {
/// A boolean. Just a boolean
Bool(bool),
/// Signed 32-bit integer
I32(i32),
/// 32-bit single precision floating point
/// can be used for aspect ratio or luminance
F32(f32),
/// Vector for nested multidimensional
Vec(Vec<FeatureResult>),
/// Standard RGBA color
Rgba(f32, f32, f32, f32),
/// Indices intended for the usage in histograms
Indices(Vec<u64>),
///A Character :)
Char(char),
///A String ;)
String(String),
///a f32 between 0 and 1 where 1 is 100% and 0 is 0%
Percent(f32),
}
impl Default for FeatureResult {
fn default() -> Self {
FeatureResult::Bool(false)
}
}
/// For some feature return type we want to implement a custom compare function
impl PartialEq for FeatureResult {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Bool(l0), Self::Bool(r0)) => l0 == r0,
(Self::I32(l0), Self::I32(r0)) => l0 == r0,
(Self::F32(l0), Self::F32(r0)) => l0 == r0,
(Self::Vec(l0), Self::Vec(r0)) => l0 == r0,
(Self::Rgba(l0, l1, l2, l3), Self::Rgba(r0, r1, r2, r3)) => {
l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3
}
(Self::Indices(l), Self::Indices(r)) => l == r,
(Self::Char(l0), Self::Char(r0)) => l0 == r0,
(Self::String(l), Self::String(r)) => l == r,
(Self::Percent(l0), Self::Percent(r0)) => l0 == r0,
_ => false,
}
}
}
///in this trait we compare the types to get the similarity between them where 1 is identical and 0 is completly different
///
/// the Vec type compares each member recursive.
/// the Rgba type returns the Delta E similarity of the Colors
/// the Indices type is compared with the cosines similarity
/// the Percent type returns the 1 - difference
///
///
impl WeightedCmp for FeatureResult {
fn weighted(&self, other: &Self) -> f32 {
match (self, other) {
(Self::Bool(l0), Self::Bool(r0)) => {
if l0 == r0 {
1.
} else {
0.
}
}
(Self::I32(l0), Self::I32(r0)) => {
if l0 == r0 {
1.
} else {
0.
}
}
(Self::F32(l0), Self::F32(r0)) => {
if (l0 - r0).abs() < 1e-4 {
1.
} else {
0.
}
}
(Self::Vec(l), Self::Vec(r)) => {
if l.len() == r.len() {
let mut b: f32 = 0.;
for a in l.iter().enumerate() {
b += a.1.weighted(&r[a.0]);
}
b / l.len() as f32
} else {
0.
}
}
(Self::Rgba(l0, l1, l2, _), Self::Rgba(r0, r1, r2, _)) => {
let lableft = rgb_to_lab(vec![*l0, *l1, *l2]);
let labright = rgb_to_lab(vec![*r0, *r1, *r2]);
let mut result = ((lableft[0] - labright[0]) * (lableft[0] - labright[0])
+ (lableft[1] - labright[1]) * (lableft[1] - labright[1])
+ (lableft[2] - labright[2]) * (lableft[2] - labright[2]))
.sqrt(); //euclidian distance between two colors: Delta E
if result > 100. {
result = 0.;
} else {
result = 1. - result / 100.;
}
result
}
(Self::Indices(l), Self::Indices(r)) => {
let mut up = 0_u64;
let mut left = 0_u64;
let mut right = 0_u64;
for (a, b) in l.iter().zip(r.iter()).map(|(a, b)| (a, b)) {
left += a * a;
right += b * b;
up += a * b;
}
let mut result = up as f32 / ((left * right) as f32).sqrt(); //cosines similarity
if result.is_nan() {
if left == right {
result = 1.;
} else {
result = 0.
}
}
result
}
(Self::Char(l0), Self::Char(r0)) => {
if l0 == r0 {
1.
} else {
0.
}
}
(Self::String(l0), Self::String(r0)) => {
if l0 == r0 {
1.
} else {
0.
}
}
(Self::Percent(l0), Self::Percent(r0)) => 1. - (l0 - r0).abs(),
_ => 0.,
}
}
}
///this function transforms rgb values to lab values
fn rgb_to_lab(rgb: Vec<f32>) -> [f32; 3] {
let r = rgb[0] / 255.0;
let g = rgb[1] / 255.0;
let b = rgb[2] / 255.0;
let r = if r > 0.04045 {
((r + 0.055) / 1.055).powf(2.4)
} else {
r / 12.92
};
let g = if g > 0.04045 {
((g + 0.055) / 1.055).powf(2.4)
} else {
g / 12.92
};
let b = if b > 0.04045 {
((b + 0.055) / 1.055).powf(2.4)
} else {
b / 12.92
};
let x = r * 0.4124 + g * 0.3576 + b * 0.1805;
let y = r * 0.2126 + g * 0.7152 + b * 0.0722;
let z = r * 0.0193 + g * 0.1192 + b * 0.9505;
let x = x / 0.95047;
let y = y / 1.0;
let z = z / 1.08883;
let x = if x > 0.008856 {
x.powf(1.0 / 3.0)
} else {
(7.787 * x) + (16.0 / 116.0)
};
let y = if y > 0.008856 {
y.powf(1.0 / 3.0)
} else {
(7.787 * y) + (16.0 / 116.0)
};
let z = if z > 0.008856 {
z.powf(1.0 / 3.0)
} else {
(7.787 * z) + (16.0 / 116.0)
};
let l = (116.0 * y) - 16.0;
let a = 500.0 * (x - y);
let b = 200.0 * (y - z);
[l, a, b]
}
pub type FeatureGenerator = fn(Arc<Image<f32>>) -> (String, FeatureResult);
///The Database stores the images with the feature generators.
///It also stores the threadpool
///the images of the Database can get serialized using Serde_Json. the complete Database cant get serialized
#[derive(Default)]
pub struct Database {
images: IndexedImages,
/// keep feature generator for the case when we add a new image
/// this field is not serialized and needs to be wrapped in an option
generators: Vec<FeatureGenerator>,
threadpool: ThreadPool<Arc<Image<f32>>, (String, FeatureResult)>,
}
impl Database {
///This function search the Database after the Similarity to a given Image in a specific feature.
/// It returns a Vector of all images and a f32 value which represents the Similarity in percent.
///
pub fn search(
&self,
imagepath: &Path,
feature: FeatureGenerator,
) -> Result<Vec<(PathBuf, f32)>, &'static str> {
self.images.search(imagepath, feature)
}
///the new function generates a new Database out of a vector of the Paths of the Images and a Vector of features
pub fn new(
imagepaths: &Vec<PathBuf>,
features: Vec<FeatureGenerator>,
) -> Result<Self, &'static str> {
let mut threadpool = ThreadPool::new();
let images = match IndexedImages::new(imagepaths, &features, &mut threadpool) {
Ok(images) => images,
Err(e) => return Err(e),
};
Ok(Self {
images,
generators: features,
threadpool,
})
}
/// Limit the amount of threads to use when processing features
pub fn limit_thread_usage(&mut self, limit: NonZeroUsize) {
self.threadpool.set_limt(limit);
}
/// Register the supplied generators.
/// All previously registered generators will be replaced with the new generators
pub fn register_generators(&mut self, generators: Vec<FeatureGenerator>) {
self.generators = generators;
}
/// with add_image you can add images in a existing database.
/// databases from a file are read only.
pub fn add_image(&mut self, path: &Path) -> Result<(), &'static str> {
if !self.generators.is_empty() {
self.images
.add_image(path, &self.generators, &mut self.threadpool)
} else {
panic!("database without generator functions is immutable")
}
}
/// with from_file you can generate a Database out of a given path to a serialized database
pub fn from_file(path: &Path) -> Self {
let filestring = fs::read_to_string(path).expect("can't read that file");
let images = serde_json::from_str::<IndexedImages>(&filestring)
.expect("unable to deserialize the file");
Self {
images,
generators: Vec::new(),
threadpool: ThreadPool::new(),
}
}
pub fn write_to_file(&self, path: &Path) {
let filestring = serde_json::to_string(&self.images).expect("unable to serialize the file");
fs::write(path, filestring).expect("unable to write the file");
}
}
///IndexedImages stores the images of the Database and is serializable
#[derive(Serialize, Deserialize, Default, PartialEq, Debug)]
struct IndexedImages {
images: HashMap<PathBuf, HashMap<String, FeatureResult>>,
}
impl IndexedImages {
///the new function generates all images and generates every feature so it can store these.
fn new(
imagepaths: &Vec<PathBuf>,
features: &[FeatureGenerator],
threadpool: &mut ThreadPool<Arc<Image<f32>>, (String, FeatureResult)>,
) -> Result<Self, &'static str> {
let mut images_with_feats = HashMap::new();
for path in imagepaths {
let image = match crate::image_loader::image_loader(path) {
Ok(image) => Arc::new(image),
Err(desc) => return Err(desc),
};
let mut feats = HashMap::new();
for generator in features.iter() {
threadpool.enqueue(Task::new(image.clone(), *generator));
}
let vec = threadpool.get_results();
for (name, result) in vec {
feats.insert(name, result);
}
images_with_feats.insert(image.path().clone(), feats);
}
Ok(Self {
images: images_with_feats,
})
}
///This function search the Database after the Similarity to a given Image in a specific feature.
/// It returns a Vector of all images and a f32 value which represents the Similarity in percent.
///
fn search(
&self,
imagepath: &Path,
feature: FeatureGenerator,
) -> Result<Vec<(PathBuf, f32)>, &'static str> {
let image = match crate::image_loader::image_loader(imagepath) {
Ok(image) => Arc::new(image),
Err(desc) => return Err(desc),
};
let search_feat = feature(image);
let mut result: Vec<(PathBuf, f32)> = Vec::new();
for image in &self.images {
for feat in image.1 {
if search_feat.0 == *feat.0 {
result.push((image.0.clone(), search_feat.1.weighted(feat.1)));
}
}
}
Ok(result)
}
///this function lets you add images to the Indexed Image struct
fn add_image(
&mut self,
path: &Path,
generator: &Vec<FeatureGenerator>,
threadpool: &mut ThreadPool<Arc<Image<f32>>, (String, FeatureResult)>,
) -> Result<(), &'static str> {
let image = match crate::image_loader::image_loader(path) {
Ok(image) => Arc::new(image),
Err(desc) => return Err(desc),
};
let mut feats = HashMap::new();
for gen in generator {
threadpool.enqueue(Task::new(image.clone(), *gen));
}
let vec = threadpool.get_results();
for (name, result) in vec {
feats.insert(name, result);
}
self.images.insert(image.path().clone(), feats);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
///this function tests the Serialization of the Database
#[test]
fn conversion() {
let mut images: HashMap<PathBuf, HashMap<String, FeatureResult>> = HashMap::new();
let mut feat: HashMap<String, FeatureResult> = HashMap::new();
feat.insert(String::from("average-brightness"), FeatureResult::F32(0.0));
images.insert(PathBuf::new(), feat);
let data = IndexedImages { images };
let _as_json = serde_json::to_string(&data).expect("couldnt convert");
println!("{:?}", _as_json);
let data_after_conversion =
serde_json::from_str::<IndexedImages>(&_as_json).expect("couldnt convert from string");
assert_eq!(data, data_after_conversion);
}
///this function tests Edgecases for the cosine_similarity in the weightet function
#[test]
fn cosine_similarity() {
let vec1 = FeatureResult::Indices(vec![1, 3, 4]);
let vec2 = FeatureResult::Indices(vec![1, 3, 4]);
assert_eq!(1., vec1.weighted(&vec2)); // both are identical
let vec2 = FeatureResult::Indices(vec![0, 0, 0]);
assert_eq!(0., vec1.weighted(&vec2)); // one is 0
let vec1 = FeatureResult::Indices(vec![0, 0, 0]);
assert_eq!(1., vec1.weighted(&vec2)); // both are 0
assert_eq!(1., vec2.weighted(&vec1)); // it shouldn't change if the Values are switched
let vec1 = FeatureResult::Indices(vec![7, 3, 4]);
let vec2 = FeatureResult::Indices(vec![1, 5, 2]);
assert_eq!(vec1.weighted(&vec2), vec2.weighted(&vec1));
println!("{:?}", vec1.weighted(&vec2));
let mut vec1 = vec![5; 9999];
vec1.push(1);
let vec1 = FeatureResult::Indices(vec1);
let vec2 = FeatureResult::Indices(vec![7; 10000]);
println!("{:?}", vec1.weighted(&vec2));
}
///this function tests all of the weighted function
#[test]
fn weighted() {
let vec1 = FeatureResult::Vec(vec![
FeatureResult::Bool(true),
FeatureResult::Char('c'),
FeatureResult::Vec(vec![FeatureResult::Percent(0.5)]),
FeatureResult::F32(44.543),
]);
let vec2 = FeatureResult::Vec(vec![
FeatureResult::Bool(true),
FeatureResult::Char('c'),
FeatureResult::Vec(vec![FeatureResult::Percent(0.5)]),
FeatureResult::F32(44.543),
]);
assert_eq!(1., vec2.weighted(&vec1));
let vec2 = FeatureResult::Vec(vec![
FeatureResult::Bool(true),
FeatureResult::Char('c'),
FeatureResult::F32(44.543),
FeatureResult::Vec(vec![FeatureResult::Percent(0.5)]),
]);
assert_eq!(0.5, vec2.weighted(&vec1));
println!("{:?}", vec1.weighted(&vec2));
let value1 = FeatureResult::F32(44.543);
let value2 = FeatureResult::F32(44.543);
assert_eq!(1., value1.weighted(&value2));
let value1 = FeatureResult::Bool(true);
let value2 = FeatureResult::Bool(false);
assert_eq!(0., value1.weighted(&value2));
let value1 = FeatureResult::String(String::from("Testing"));
let value2 = FeatureResult::String(String::from("notTesting"));
assert_eq!(0., value1.weighted(&value2));
let value2 = FeatureResult::String(String::from("Testing"));
assert_eq!(1., value1.weighted(&value2));
}
///this test is for the rgba values in the weighted function
#[test]
fn weighted_rgba() {
let value1 = FeatureResult::Rgba(32.6754, 42.432, 43.87, 255.);
let value2 = FeatureResult::Rgba(32.6754, 42.432, 43.87, 255.);
assert_eq!(1., value1.weighted(&value2));
let value1 = FeatureResult::Rgba(255., 255., 0., 255.);
let value2 = FeatureResult::Rgba(0., 0., 0., 255.);
//assert_eq!(1., value1.weighted(&value2)) ;
println!("Yellow to Black: {:?}", value1.weighted(&value2));
let value1 = FeatureResult::Rgba(255., 255., 0., 255.);
let value2 = FeatureResult::Rgba(200., 255., 55., 255.);
//assert_eq!(1., value1.weighted(&value2)) ;
println!("yellow to light green: {:?}", value1.weighted(&value2));
let value1 = FeatureResult::Rgba(3., 8., 255., 255.);
let value2 = FeatureResult::Rgba(3., 106., 255., 255.);
//assert_eq!(1., value1.weighted(&value2)) ;
println!("blue to dark blue: {:?}", value1.weighted(&value2));
let value1 = FeatureResult::Rgba(255., 106., 122., 255.);
let value2 = FeatureResult::Rgba(255., 1., 28., 255.);
//assert_eq!(1., value1.weighted(&value2)) ;
println!("Red to light red: {:?}", value1.weighted(&value2));
}
}

82
tests/integration_test.rs Normal file
View File

@ -0,0 +1,82 @@
use std::{path::Path, sync::Arc};
use imsearch::{
image::Image,
search_index::{Database, FeatureGenerator, FeatureResult},
};
fn average_brightness(image: Arc<Image<f32>>) -> (String, FeatureResult) {
let bright = image
.pixels()
.iter()
.map(|(r, g, b, _)| (r + g + b) / 3.0 / 255.0)
.sum::<f32>()
/ image.pixels().len() as f32;
(
String::from("average_brightness"),
FeatureResult::Percent(bright),
)
}
#[test]
fn test_database_basic() {
let files: Vec<std::path::PathBuf> = std::fs::read_dir("res/integration/")
.unwrap()
.map(|f| f.unwrap().path())
.collect();
let feats: Vec<FeatureGenerator> = vec![average_brightness];
let db = Database::new(&files, feats).unwrap();
for results in db
.search(
std::path::Path::new("res/integration/gray_image.png"),
average_brightness,
)
.unwrap()
{
println!(
"path: {} similarity: {}",
results.0.as_os_str().to_str().unwrap(),
results.1
);
}
}
#[test]
fn test_database_files() {
let json = Path::new("db.json");
{
let files: Vec<std::path::PathBuf> = std::fs::read_dir("res/integration/")
.unwrap()
.map(|f| f.unwrap().path())
.collect();
let feats: Vec<FeatureGenerator> = vec![average_brightness];
let db = Database::new(&files, feats).unwrap();
db.write_to_file(json);
}
{
let db = Database::from_file(json);
for results in db
.search(
std::path::Path::new("res/integration/gray_image.png"),
average_brightness,
)
.unwrap()
{
println!(
"path: {} similarity: {}",
results.0.as_os_str().to_str().unwrap(),
results.1
);
}
}
}