├── .gitignore ├── example_images ├── left.jpg ├── right.jpg ├── simple.gif ├── PY3D0001.MPO ├── cross_eye.jpg ├── align_shift.gif ├── anaglyph_color.jpg ├── anaglyph_gray.jpg ├── tv_left_right.jpg ├── tv_over_under.jpg ├── anaglyph_dubois.jpg ├── anaglyph_wimmer.jpg └── anaglyph_half_color.jpg ├── workspace.code-workspace ├── stereoscopy ├── __main__.py └── __init__.py ├── setup.py ├── .vscode └── settings.json ├── README.md ├── gimp_plugin └── stereoscopy-gimp.py └── LICENCE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | *.pyc 3 | -------------------------------------------------------------------------------- /example_images/left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/left.jpg -------------------------------------------------------------------------------- /example_images/right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/right.jpg -------------------------------------------------------------------------------- /example_images/simple.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/simple.gif -------------------------------------------------------------------------------- /example_images/PY3D0001.MPO: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/PY3D0001.MPO -------------------------------------------------------------------------------- /example_images/cross_eye.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/cross_eye.jpg -------------------------------------------------------------------------------- /workspace.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /example_images/align_shift.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/align_shift.gif -------------------------------------------------------------------------------- /example_images/anaglyph_color.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/anaglyph_color.jpg -------------------------------------------------------------------------------- /example_images/anaglyph_gray.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/anaglyph_gray.jpg -------------------------------------------------------------------------------- /example_images/tv_left_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/tv_left_right.jpg -------------------------------------------------------------------------------- /example_images/tv_over_under.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/tv_over_under.jpg -------------------------------------------------------------------------------- /example_images/anaglyph_dubois.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/anaglyph_dubois.jpg -------------------------------------------------------------------------------- /example_images/anaglyph_wimmer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/anaglyph_wimmer.jpg -------------------------------------------------------------------------------- /example_images/anaglyph_half_color.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2sh/StereoscoPy/HEAD/example_images/anaglyph_half_color.jpg -------------------------------------------------------------------------------- /stereoscopy/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # StereoscoPy, stereoscopic 3D image creator 5 | # 6 | # Copyright (C) 2016-2024 2sh 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | # 21 | 22 | from __future__ import absolute_import, division, print_function 23 | 24 | from . import _main 25 | 26 | _main() 27 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import setuptools 5 | 6 | with open("README.md", "r") as f: 7 | long_description = f.read() 8 | 9 | setuptools.setup( 10 | name="stereoscopy", 11 | version="2.2.0", 12 | 13 | author="2sh", 14 | author_email="contact@2sh.me", 15 | 16 | description="StereoscoPy, stereoscopic 3D image creator", 17 | long_description=long_description, 18 | long_description_content_type="text/markdown", 19 | 20 | url="https://github.com/2sh/StereoscoPy", 21 | 22 | packages=["stereoscopy"], 23 | 24 | install_requires=["Pillow"], 25 | extras_require={ 26 | "auto_align": ["opencv-python", "numpy"] 27 | }, 28 | python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", 29 | classifiers=( 30 | "Programming Language :: Python :: 2", 31 | "Programming Language :: Python :: 2.7", 32 | 33 | "Programming Language :: Python :: 3", 34 | "Programming Language :: Python :: 3.4", 35 | "Programming Language :: Python :: 3.5", 36 | "Programming Language :: Python :: 3.6", 37 | "Programming Language :: Python :: 3.7", 38 | 39 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 40 | "Operating System :: OS Independent", 41 | "Topic :: Multimedia :: Graphics" 42 | ), 43 | 44 | entry_points={"console_scripts":["StereoscoPy=stereoscopy:_main"]} 45 | ) 46 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/dist": true, 4 | "**/dest": true, 5 | "**/build": true, 6 | "**/target": true, 7 | }, 8 | "files.trimTrailingWhitespace": true, 9 | "files.insertFinalNewline": true, 10 | "files.eol": "\n", 11 | "editor.rulers": [ 12 | { 13 | // Max comment line length (PEP 8) 14 | "column": 72, 15 | "color": "#6A995533" 16 | }, 17 | { 18 | // Ideal max line length (PEP 8) 19 | "column": 79, 20 | "color": "#ffffff22" 21 | }, 22 | { 23 | /* 24 | Still fully visible line when the Code editor window is 25 | half-width of an HD monitor under these conditions: 26 | - Activity bar position on the side 27 | - Hidden primary and secondary side bars 28 | - Minimap 29 | - Font size: 14 30 | - Font family: Droid Sans Mono 31 | - Under 10000 lines 32 | Using Code's split editor allows for 88 characters, only 2 more 33 | Also, 79 + (79 - 72) = 86 34 | */ 35 | "column": 86, 36 | "color": "#ffff4422" 37 | } 38 | ], 39 | "editor.detectIndentation": false, 40 | "editor.tabSize": 2, 41 | "editor.insertSpaces": true, 42 | "[python]": { 43 | "editor.tabSize": 4, 44 | "editor.insertSpaces": false, // for this project 45 | }, 46 | "[jsonc][json]": { 47 | "editor.defaultFormatter": "vscode.json-language-features", 48 | }, 49 | "[typescript][javascript]": { 50 | "editor.defaultFormatter": "vscode.typescript-language-features", 51 | }, 52 | "javascript.format.insertSpaceAfterConstructor": true, 53 | "typescript.format.insertSpaceAfterConstructor": true, 54 | "javascript.format.placeOpenBraceOnNewLineForControlBlocks": true, 55 | "typescript.format.placeOpenBraceOnNewLineForControlBlocks": true, 56 | "javascript.format.placeOpenBraceOnNewLineForFunctions": true, 57 | "typescript.format.placeOpenBraceOnNewLineForFunctions": true, 58 | "javascript.format.semicolons": "remove", 59 | "typescript.format.semicolons": "remove", 60 | } 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StereoscoPy 2 | This is a Python script/library for 3 | converting two images into a stereoscopic 3D image: 4 | anaglyph, 5 | side-by-side (cross-eye and parallel), 6 | over/under, 7 | wiggle GIF, 8 | interlaced and 9 | checkerboard. 10 | 11 | ## Requirements 12 | * Python 3.4+ or Python 2.7+ 13 | * Pillow 14 | * cv2 (optional for auto align) 15 | * numpy (optional for auto align) 16 | 17 | ## Installation 18 | From the Python Package Index: 19 | ``` 20 | pip install stereoscopy 21 | ``` 22 | 23 | With the optional requirements for the auto align feature: 24 | ``` 25 | pip install "stereoscopy[auto_align]" 26 | ``` 27 | 28 | Or download and run: 29 | ``` 30 | python setup.py install 31 | ``` 32 | 33 | ## Command-Line 34 | ### Help 35 | ``` 36 | StereoscoPy --help 37 | ``` 38 | 39 | ### Cross-eyed (Right/Left) 40 | With white 5px wide border and image division. Auto aligned, resized to 41 | be 450 pixels in width and shifted horizontally by 1 pixel. 42 | ``` 43 | StereoscoPy -A -R 400 0 -S 1 0 -x --div 5 --border 5 --bg 255 255 255 0 left.jpg right.jpg cross_eye.jpg 44 | ``` 45 | ![](/example_images/cross_eye.jpg?raw=true "Cross eyed") 46 | 47 | ### Anaglyph 48 | For red-cyan glasses, there are various methods for creating anaglyphs 49 | available. 50 | ``` 51 | StereoscoPy -A -R 400 0 -S 1 0 -a left.jpg right.jpg anaglyph_wimmer.jpg 52 | StereoscoPy -A -R 400 0 -S 1 0 -am dubois left.jpg right.jpg anaglyph_dubois.jpg 53 | StereoscoPy -A -R 400 0 -S 1 0 -am gray left.jpg right.jpg anaglyph_gray.jpg 54 | StereoscoPy -A -R 400 0 -S 1 0 -am color left.jpg right.jpg anaglyph_color.jpg 55 | StereoscoPy -A -R 400 0 -S 1 0 -am half-color left.jpg right.jpg anaglyph_half_color.jpg 56 | ``` 57 | ![](/example_images/anaglyph_wimmer.jpg?raw=true "Wimmer anaglyph") 58 | ![](/example_images/anaglyph_dubois.jpg?raw=true "Dubois anaglyph") 59 | ![](/example_images/anaglyph_gray.jpg?raw=true "Gray anaglyph") 60 | ![](/example_images/anaglyph_color.jpg?raw=true "Color anaglyph") 61 | ![](/example_images/anaglyph_half_color.jpg?raw=true "Half-Color anaglyph") 62 | 63 | The Dubois anaglyph method for amber-blue glasses. 64 | ``` 65 | StereoscoPy -am dubois --cs amber-blue left.jpg right.jpg anaglyph_dubois_ab.jpg 66 | ``` 67 | 68 | ### Wiggle GIF 69 | Without alignment 70 | ``` 71 | StereoscoPy -R 400 0 -wt 400 left.jpg right.jpg simple.gif 72 | ``` 73 | ![](/example_images/simple.gif?raw=true "Simple") 74 | 75 | Shifting an image moves the right image in relation to the left image. 76 | An images can be shifted after the auto align to change its center. 77 | ``` 78 | StereoscoPy -A -R 400 0 -S 1 0 -wt 200 left.jpg right.jpg align_shift.gif 79 | ``` 80 | ![](/example_images/align_shift.gif?raw=true "Aligned and shifted") 81 | 82 | ### Squashed Parallel (Left/Right) and Top/Bottom for TVs 83 | ``` 84 | StereoscoPy -A -R 400 0 -S 1 0 -ps left.jpg right.jpg tv_left_right.jpg 85 | StereoscoPy -A -R 400 0 -S 1 0 -os left.jpg right.jpg tv_over_under.jpg 86 | ``` 87 | ![](/example_images/tv_left_right.jpg?raw=true "Top/Bottom") 88 | ![](/example_images/tv_over_under.jpg?raw=true "Left/Right") 89 | 90 | ### Two separate image outputs 91 | Before converting to the stereoscopic outputs, I find this (or a slow 92 | wiggle GIF) to be a nice way to check for the correct dimensions, shift 93 | and rotation by switching between the two output images in an image 94 | viewer. 95 | ``` 96 | StereoscoPy --shift 19 30 --crop 20% 0 0 0 --resize 1920 1080 --offset 100% --parallel left.jpg right.jpg out1.jpg out2.jpg 97 | ``` 98 | 99 | ### MPO 100 | Saving as an MPO file for the Nintendo 3DS. 101 | ``` 102 | StereoscoPy -A -R 400 240 -S 1 0 left.jpg right.jpg PY3D0001.MPO 103 | ``` 104 | 105 | ### Misc 106 | 20% cropped from the top, resized to 1920x1080 and offset to the right 107 | by 100%. 108 | ``` 109 | StereoscoPy --crop 20% 0 0 0 --resize 1920 1080 --offset 100% --cross-eye left.jpg right.jpg out.jpg 110 | StereoscoPy -C 20% 0 0 0 -R 1920 1080 -O 100% -x left.jpg right.jpg out.jpg 111 | ``` 112 | 113 | 20% cropped from left and right and resized to be 1080 high and 0 width 114 | to preserve the aspect ratio. 115 | ``` 116 | StereoscoPy -R 0 1080 -C 0 20% 0 20% -o left.jpg right.jpg out.jpg 117 | ``` 118 | -------------------------------------------------------------------------------- /gimp_plugin/stereoscopy-gimp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # StereoscoPy for GIMP 5 | # 6 | # Copyright (C) 2016-2024 2sh 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | # 21 | 22 | from gimpfu import * 23 | 24 | from PIL import Image 25 | 26 | import stereoscopy 27 | 28 | 29 | _anaglyph_methods = [ 30 | ("Wimmer", "wimmer"), 31 | ("Gray", "gray"), 32 | ("Color", "color"), 33 | ("Half Color", "half-color"), 34 | ("Dubois", "dubois") 35 | ] 36 | 37 | _anaglyph_color_schemes = [ 38 | ("Red/Cyan", "red-cyan"), 39 | ("Red/Green", "red-green"), 40 | ("Red/Blue", "red-blue"), 41 | ("Green/Magenta", "green-magenta"), 42 | ("Amber/Blue", "amber-blue"), 43 | ("Magenta/Cyan", "magenta-cyan") 44 | ] 45 | 46 | _anaglyph_luma_coding = [ 47 | ("Rec. 709", stereoscopy.ANAGLYPH_LUMA_REC709), 48 | ("Rec. 601", stereoscopy.ANAGLYPH_LUMA_REC601), 49 | ("RGB", stereoscopy.ANAGLYPH_LUMA_RGB) 50 | ] 51 | 52 | 53 | def _create_stereoscopic_image(func, name, layers): 54 | pdb.gimp_progress_set_text("Preparing...") 55 | 56 | width = layers[0].image.width 57 | height = layers[0].image.height 58 | 59 | p_images = [] 60 | for i, layer in enumerate(layers): 61 | if i > 1: 62 | break 63 | 64 | pdb.gimp_image_undo_freeze(layer.image) 65 | temp = layer.copy() 66 | layer.image.add_layer(temp, 0) 67 | temp.resize(width, height, *layer.offsets) 68 | 69 | rgn = temp.get_pixel_rgn(0, 0, temp.width, temp.height, False) 70 | 71 | if temp.has_alpha: 72 | mode = "RGBA" 73 | else: 74 | mode = "RGB" 75 | 76 | p_image = Image.frombytes(mode, (temp.width, temp.height), 77 | rgn[0:temp.width, 0:temp.height]) 78 | p_images.append(p_image) 79 | layer.image.remove_layer(temp) 80 | pdb.gimp_image_undo_thaw(layer.image) 81 | 82 | pdb.gimp_progress_set_text("Creating...") 83 | 84 | p_image = func(p_images) 85 | 86 | width, height = p_image.size 87 | 88 | pdb.gimp_progress_set_text("Displaying...") 89 | 90 | image = gimp.Image(width, height, RGB) 91 | image.disable_undo() 92 | 93 | layer = gimp.Layer(image, name, 94 | width, height, RGB_IMAGE, 100, NORMAL_MODE) 95 | image.add_layer(layer, 0) 96 | 97 | if p_image.mode == "RGBA": 98 | layer.add_alpha() 99 | 100 | rgn = layer.get_pixel_rgn(0, 0, width, height) 101 | rgn[0:width, 0:height] = p_image.tobytes() 102 | 103 | image.enable_undo() 104 | gimp.Display(image) 105 | gimp.displays_flush() 106 | 107 | def create_anaglyph(image, drawable, left, right, 108 | method, color_scheme, luma_coding): 109 | method = _anaglyph_methods[method][1] 110 | color_scheme = _anaglyph_color_schemes[color_scheme][1] 111 | luma_coding = _anaglyph_luma_coding[luma_coding][1] 112 | 113 | def func(images): 114 | return stereoscopy.create_anaglyph(images, 115 | method, color_scheme, luma_coding) 116 | 117 | _create_stereoscopic_image(func, "Anaglyph", (left, right)) 118 | 119 | def create_side_by_side_image(image, drawable, left, right, 120 | method, squash, divider): 121 | 122 | def func(images): 123 | is_horizontal = method == 0 or method == 1 124 | 125 | if squash: 126 | for i in range(len(images)): 127 | images[i] = stereoscopy.squash(images[i], is_horizontal) 128 | 129 | if method == 0 or method == 3: 130 | images.reverse() 131 | 132 | return stereoscopy.create_side_by_side_image(images, 133 | is_horizontal, int(divider)) 134 | 135 | _create_stereoscopic_image(func, "Side-by-side", (left, right)) 136 | 137 | def create_patterned_image(image, drawable, left, right, 138 | method, odd, width): 139 | method = [stereoscopy.PATTERN_INTERLACED_H, 140 | stereoscopy.PATTERN_INTERLACED_V, 141 | stereoscopy.PATTERN_CHECKERBOARD][method] 142 | 143 | def func(images): 144 | return stereoscopy.create_patterned_image(images, 145 | method, width, not odd) 146 | 147 | _create_stereoscopic_image(func, "Patterned", (left, right)) 148 | 149 | def create_wiggle_animation(image, drawable, 150 | duration): 151 | image = pdb.gimp_image_duplicate(image) 152 | 153 | for layer in image.layers[1:-1]: 154 | image.add_layer(layer.copy(), 0) 155 | 156 | image_duration = int(round(duration/len(image.layers))) 157 | 158 | for layer in image.layers: 159 | layer.name += " ({}ms)".format(image_duration) 160 | 161 | gimp.Display(image) 162 | gimp.displays_flush() 163 | 164 | register( 165 | "Anaglyph", 166 | "Create an anaglypth", 167 | "Create an anaglypth", 168 | "2sh", 169 | "2sh", 170 | "2018-2024", 171 | "/Filters/StereoscoPy/Anaglyph...", 172 | "*", 173 | [ 174 | (PF_LAYER, "left", "Left image", None), 175 | (PF_LAYER, "right", "Right image", None), 176 | (PF_OPTION, "method", "Method", 0, 177 | [t for t,_ in _anaglyph_methods]), 178 | (PF_OPTION, "color_scheme", "Color Scheme", 0, 179 | [t for t,_ in _anaglyph_color_schemes]), 180 | (PF_OPTION, "luma_coding", "Luma Coding", 0, 181 | [t for t,_ in _anaglyph_luma_coding]) 182 | ], 183 | [], 184 | create_anaglyph) 185 | 186 | register( 187 | "Side-by-side", 188 | "Create a side-by-side image", 189 | "Create a side-by-side image", 190 | "2sh", 191 | "2sh", 192 | "2018-2024", 193 | "/Filters/StereoscoPy/Side-by-side...", 194 | "*", 195 | [ 196 | (PF_LAYER, "left", "Left image", None), 197 | (PF_LAYER, "right", "Right image", None), 198 | (PF_OPTION, "method", "Method", 0, [ 199 | "Right/Left (Cross-eye)", 200 | "Left/Right (Parallel, VR)", 201 | "Over/Under", 202 | "Under/Over"]), 203 | (PF_TOGGLE, "squash", "Squash", False), 204 | (PF_SPINNER, "divider", "Divider", 0, (0, 9999999, 1)) 205 | ], 206 | [], 207 | create_side_by_side_image) 208 | 209 | register( 210 | "Patterned", 211 | "Create a patterned image", 212 | "Create a patterned image", 213 | "2sh", 214 | "2sh", 215 | "2018-2024", 216 | "/Filters/StereoscoPy/Patterned...", 217 | "*", 218 | [ 219 | (PF_LAYER, "left", "Left image", None), 220 | (PF_LAYER, "right", "Right image", None), 221 | (PF_OPTION, "method", "Method", 0, [ 222 | "Interlaced horizontally", 223 | "Interlaced vertically", 224 | "Checkerboard"]), 225 | (PF_OPTION, "odd", "Order", 0, [ 226 | "Even", 227 | "Odd"]), 228 | (PF_SPINNER, "width", "Width", 1, (1, 9999999, 1)) 229 | ], 230 | [], 231 | create_patterned_image) 232 | 233 | register( 234 | "Wiggle", 235 | "Create a wiggle animation", 236 | "Create a wiggle animation", 237 | "2sh", 238 | "2sh", 239 | "2018-2024", 240 | "/Filters/StereoscoPy/Wiggle...", 241 | "*", 242 | [ 243 | (PF_SPINNER, "duration", "Duration (ms)", 300, (1, 9999999, 1)) 244 | ], 245 | [], 246 | create_wiggle_animation) 247 | 248 | main() 249 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /stereoscopy/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # StereoscoPy, stereoscopic 3D image creator 5 | # 6 | # Copyright (C) 2016-2024 2sh 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | # 21 | 22 | from __future__ import absolute_import, division, print_function 23 | 24 | from PIL import Image, ImageChops, ImageMath 25 | import math 26 | 27 | try: 28 | from importlib.util import find_spec 29 | except: 30 | from pkgutil import find_loader as find_spec 31 | 32 | if(find_spec("cv2") is not None and find_spec("numpy") is not None): 33 | import cv2 34 | import numpy 35 | 36 | def to_pixels(value, reference): 37 | """Convert a percentage to pixels. 38 | 39 | Args: 40 | value: The value of either pixels or percentage ending with a 41 | percentage sign. 42 | reference: The value of 100% 43 | 44 | Returns: 45 | The pixel value. 46 | """ 47 | try: 48 | if value.endswith("%"): 49 | return int(round((int(value[:-1])/100)*reference)) 50 | except: 51 | pass 52 | return int(value) 53 | 54 | def fix_orientation(image): 55 | """Fix the orientation of an image using its exif data. 56 | 57 | Args: 58 | image: A PIL image. 59 | 60 | Returns: 61 | The reorientated PIL image. 62 | """ 63 | try: 64 | orientation = image._getexif()[274] 65 | except: 66 | return image 67 | 68 | if orientation == 3: 69 | return image.transpose(Image.ROTATE_180) 70 | elif orientation == 6: 71 | return image.transpose(Image.ROTATE_270) 72 | elif orientation == 8: 73 | return image.transpose(Image.ROTATE_90) 74 | else: 75 | return image 76 | 77 | def _get_rotation_coordinates(matrix, size): 78 | xs = [0] 79 | ys = [0] 80 | for x, y in [(0, size[1]), (size[0], 0), size]: 81 | xs.append(matrix[0][0]*x + matrix[0][1]*y) 82 | ys.append(matrix[1][0]*x + matrix[1][1]*y) 83 | return xs, ys 84 | 85 | def transform(images, matrices, shrink=False): 86 | """Transform the images. 87 | 88 | The images are transformed by their matrices and either expanded or 89 | shruk to the same size. 90 | 91 | Args: 92 | images: The PIL images. 93 | matrices: The matrices for each image. 94 | shrink: Whether the image is shrunk into or expanded around the 95 | resulting picture. 96 | 97 | Returns: 98 | The transformed images. 99 | """ 100 | output = [] 101 | 102 | output_width = 0 103 | output_height = 0 104 | matrices = list(matrices) 105 | for i, image in enumerate(images): 106 | matrix = [] 107 | for row in matrices[i]: 108 | matrix.append(list(row)) 109 | matrices[i] = matrix 110 | 111 | aspect_ratio = image.width / image.height 112 | 113 | xs, ys = _get_rotation_coordinates(matrix, image.size) 114 | 115 | min_x = min(xs) 116 | max_x = max(xs) 117 | min_y = min(ys) 118 | max_y = max(ys) 119 | 120 | expanded_width = max_x - min_x 121 | expanded_height = max_y - min_y 122 | 123 | a, b, h = matrix[0] 124 | c, d, k = matrix[1] 125 | 126 | h += min_x+(expanded_width-image.width)/2 127 | k += min_y+(expanded_height-image.height)/2 128 | 129 | margin_x = abs((d*h-b*k)/(a*d-b*c)) 130 | margin_y = abs((a*k-c*h)/(a*d-b*c)) 131 | 132 | if shrink: 133 | rotated_aspect_ratio = expanded_width / expanded_height 134 | 135 | if aspect_ratio < 1: 136 | total_height = image.width / rotated_aspect_ratio 137 | else: 138 | total_height = image.height 139 | angle = math.acos(matrix[0][0]) 140 | height = total_height / (aspect_ratio * abs(math.sin(angle)) + 141 | abs(math.cos(angle))) 142 | 143 | width = math.floor(height * aspect_ratio) - margin_x*2 144 | height = math.floor(height) - margin_y*2 145 | 146 | height_from_width = width/aspect_ratio 147 | if height_from_width < height: 148 | height = height_from_width 149 | elif height_from_width > height: 150 | width = height * aspect_ratio 151 | 152 | output_width = (min(output_width, width) 153 | if output_width else width) 154 | output_height = (min(output_height, height) 155 | if output_height else height) 156 | else: 157 | width = expanded_width + margin_x*2 158 | height = expanded_height + margin_y*2 159 | 160 | height_from_width = width/aspect_ratio 161 | if height_from_width > height: 162 | height = height_from_width 163 | elif height_from_width < height: 164 | width = height * aspect_ratio 165 | 166 | output_width = max(output_width, width) 167 | output_height = max(output_height, height) 168 | 169 | if shrink: 170 | output_width = math.floor(output_width) 171 | output_height = math.floor(output_height) 172 | else: 173 | output_width = math.ceil(output_width) 174 | output_height = math.ceil(output_height) 175 | 176 | for i, image in enumerate(images): 177 | matrix = matrices[i] 178 | x = (output_width - image.size[0]) / 2 179 | y = (output_height - image.size[1]) / 2 180 | 181 | matrix[0][2] -= matrix[0][0] * x + matrix[0][1] * y 182 | matrix[1][2] -= matrix[1][0] * x + matrix[1][1] * y 183 | 184 | output.append(image.transform((output_width, output_height), 185 | Image.AFFINE, data=matrix[0]+matrix[1], resample=Image.BICUBIC)) 186 | return output 187 | 188 | def xy_and_angle_to_matrix(xy, angle, size): 189 | """Create a 3x3 transformation matrix 190 | 191 | Args: 192 | xy: a tuple of the x and y dimensions. 193 | angle: the angle in degrees. 194 | 195 | Returns: 196 | The transformation matrix 197 | """ 198 | x, y = (xy if xy else (0, 0)) 199 | angle = math.radians(angle) 200 | c = math.cos(angle) 201 | s = math.sin(angle) 202 | h = c*x + s*y 203 | k = -s*x + c*y 204 | 205 | xs, ys = _get_rotation_coordinates(((c, s),(-s, c)), size) 206 | 207 | min_x = min(xs) 208 | max_x = max(xs) 209 | min_y = min(ys) 210 | max_y = max(ys) 211 | 212 | expanded_size = (max_x-min_x, max_y-min_y) 213 | 214 | h -= min_x+(expanded_size[0]-size[0])/2 215 | k -= min_y+(expanded_size[1]-size[1])/2 216 | 217 | return ((c, s, h), (-s, c, k), (0, 0, 1)) 218 | 219 | def combine_matrices(matrix1, matrix2): 220 | """Combine the two matrices through multiplication. 221 | 222 | Args: 223 | matrix1: The first matrix. 224 | matrix2: The second matrix. 225 | 226 | Returns: 227 | A matrix, combined from the two input matrices. 228 | """ 229 | m2_columns = list(zip(*matrix2)) 230 | return tuple([tuple([sum(a * b for a, b in zip(m1_row, m2_col)) 231 | for m2_col in m2_columns]) for m1_row in matrix1]) 232 | 233 | def find_alignments(images, iterations=20, threshold=1e-10): 234 | """Find the alignment between two images. 235 | 236 | Args: 237 | images: Two PIL images. 238 | iterations: The amount of iterations. 239 | threshold: The accuracy threshold. 240 | 241 | Returns: 242 | The alignment matrix for each image. 243 | """ 244 | ii = images 245 | tn_size = 500 246 | ratio = max(images[0].size)/tn_size 247 | 248 | images = list(images) 249 | for i in range(len(images)): 250 | images[i] = images[i].convert("L") 251 | #Runs on smaller image for speed 252 | images[i].thumbnail((tn_size, tn_size), Image.BILINEAR) 253 | images[i] = numpy.array(images[i]) 254 | 255 | criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 256 | iterations, threshold) 257 | 258 | m = numpy.eye(2, 3, dtype=numpy.float32) 259 | try: 260 | _, m = cv2.findTransformECC( 261 | images[0], images[1], m, cv2.MOTION_EUCLIDEAN, criteria, None, 5) 262 | except TypeError: 263 | _, m = cv2.findTransformECC( 264 | images[0], images[1], m, cv2.MOTION_EUCLIDEAN, criteria) 265 | 266 | m[0,2] *= ratio 267 | m[1,2] *= ratio 268 | 269 | m[0,1] /= 2 270 | m[0,2] /= 2 271 | m[1,0] /= 2 272 | m[1,2] /= 2 273 | 274 | l = ((m[0,0], -m[0,1], -m[0,2]), (-m[1,0], m[1,1], -m[1,2]), (0, 0, 1)) 275 | r = ((m[0,0], m[0,1], m[0,2]), (m[1,0], m[1,1], m[1,2]), (0, 0, 1)) 276 | 277 | return [l, r] 278 | 279 | def auto_align(images, xy_adjust=None, angle_adjust=None, shrink=False, 280 | iterations=20, threshold=1e-10): 281 | """Auto align two images. 282 | 283 | This is a convenience function using the *find_alignments*, 284 | *xy_and_angle_to_matrix*, *combine_matrices* and *transform* 285 | functions. This combines xy and angle adjustments in a single 286 | transform with the found alignment to avoid a loss of quality from 287 | multiple transforms. 288 | 289 | Args: 290 | images: Two PIL images. 291 | xy_adjust: The position adjustment as 292 | a tuple of x and y dimensions (x, y). 293 | angle_adjust: The angle adjustment 294 | in degrees for each image in a tuple (a, b). 295 | shrink: Whether the image is shrunk into or expanded around the 296 | resulting picture. 297 | iterations: The amount of iterations. 298 | threshold: The accuracy threshold. 299 | 300 | Returns: 301 | The auto aligned images. 302 | """ 303 | 304 | matrices = find_alignments(images, iterations, threshold) 305 | if xy_adjust or angle_adjust: 306 | if not xy_adjust: 307 | xy_adjust = (0, 0) 308 | if not angle_adjust: 309 | angle_adjust = (0, 0) 310 | for i in range(2): 311 | if i == 0: 312 | xy = -xy_adjust[0], -xy_adjust[1] 313 | else: 314 | xy = xy_adjust 315 | 316 | matrix = xy_and_angle_to_matrix( 317 | xy, angle_adjust[i], images[i].size) 318 | matrices[i] = combine_matrices(matrices[i], matrix) 319 | 320 | return transform(images, matrices, shrink) 321 | 322 | def crop(image, box): 323 | """Crop an image. 324 | 325 | Args: 326 | image: A PIL image. 327 | box: The amount to crop off each side. 328 | The box side order is left, top, right, bottom. 329 | 330 | Return: 331 | The cropped PIL image. 332 | """ 333 | left, top, right, bottom = box 334 | return image.crop(( 335 | to_pixels(left, image.height), 336 | to_pixels(top, image.width), 337 | image.width-to_pixels(right, image.height), 338 | image.height-to_pixels(bottom, image.width))) 339 | 340 | def resize(image, size, offset="50%"): 341 | """Resize an image. 342 | 343 | A size value that is not larger than 0 is calculated automatically 344 | to preserve the aspect ratio. 345 | 346 | Args: 347 | image: A PIL image. 348 | size: The width and height. 349 | offset: The offset from the center. 350 | 351 | Returns: 352 | The resized PIL image. 353 | """ 354 | width_ratio = size[0]/image.width 355 | height_ratio = size[1]/image.height 356 | 357 | offset_crop = None 358 | if width_ratio > height_ratio: 359 | re_size = (size[0], int(round(image.height * width_ratio))) 360 | if size[1]: 361 | offset = to_pixels(offset, re_size[1]-size[1]) 362 | offset_crop = (0, offset, size[0], size[1]+offset) 363 | elif width_ratio < height_ratio: 364 | re_size = (int(round(image.width * height_ratio)), size[1]) 365 | if size[0]: 366 | offset = to_pixels(offset, re_size[0]-size[0]) 367 | offset_crop = (offset, 0, size[0]+offset, size[1]) 368 | else: 369 | re_size = (size[0], size[1]) 370 | 371 | image = image.resize(re_size, Image.LANCZOS) 372 | if offset_crop: 373 | image = image.crop(offset_crop) 374 | return image 375 | 376 | def squash(image, horizontal): 377 | """Squash an image to be half its width or height. 378 | 379 | Args: 380 | image: A PIL image. 381 | horizontal: 382 | If to squash the image horizontal instead ofvertical. 383 | 384 | Returns: 385 | The squashed PIL image. 386 | """ 387 | if horizontal: 388 | new_size = (int(round(image.width/2)), image.height) 389 | else: 390 | new_size = (image.width, int(round(image.height/2))) 391 | return image.resize(new_size, Image.ANTIALIAS) 392 | 393 | def create_side_by_side_image(images, horizontal=True, divider_width=0): 394 | """Create a side-by-side image from two images. 395 | 396 | Args: 397 | images: Two PIL images. 398 | horizontal: 399 | If to join the images horizontal instead of vertical. 400 | divider_width: 401 | Width of a divider between the two joined images. 402 | 403 | Returns: 404 | The side-by-side PIL image. 405 | """ 406 | if horizontal: 407 | width = images[0].width * 2 + divider_width 408 | height = images[0].height 409 | r_left = images[0].width + divider_width 410 | r_top = 0 411 | else: 412 | width = images[0].width 413 | height = images[0].height * 2 + divider_width 414 | r_left = 0 415 | r_top = images[0].height + divider_width 416 | 417 | if divider_width: 418 | mode = "RGBA" 419 | else: 420 | mode = images[0].mode 421 | 422 | output = Image.new(mode, (width, height)) 423 | output.paste(images[0], (0, 0)) 424 | output.paste(images[1], (r_left, r_top)) 425 | return output 426 | 427 | 428 | ANAGLYPH_LUMA_RGB = (1/3, 1/3, 1/3) 429 | ANAGLYPH_LUMA_REC601 = (0.299, 0.587, 0.114) 430 | ANAGLYPH_LUMA_REC709 = (0.2126, 0.7152, 0.0722) 431 | 432 | _DEFAULT_AG_CS = "red-cyan" 433 | _DEFAULT_AG_LUMA = ANAGLYPH_LUMA_REC709 434 | 435 | class AnaglyphMethod: 436 | '''A class that represents an anaglyph method 437 | 438 | This class is used to create an anaglyph method with which to create 439 | anaglyph images. 440 | 441 | The built-in anaglyph methods available are constructed using the 442 | class methods *gray*, *color*, *halfColor*, *wimmer* and *dubois*. 443 | You may inherit this class to create further anaglyph methods. 444 | 445 | The available color schemes for these are "red-green", "red-blue", 446 | "red-cyan", "green-magenta", "amber-blue" and "magenta-cyan". 447 | These are the colors of the viewing glasses. The dubois class method 448 | only takes the "red-cyan", "green-magenta" and "amber-blue" color 449 | schemes. red-cyan is the default. 450 | 451 | There are 3 luma coding constants available in this module: 452 | ANAGLYPH_LUMA_RGB, ANAGLYPH_LUMA_REC601 (PAL/NTSC) and 453 | ANAGLYPH_LUMA_REC709 (HDTV). ANAGLYPH_LUMA_REC709 is the default. 454 | 455 | If a subclass overrides the constructor, it must make sure to invoke 456 | the base class constructor (Thread.__init__()). 457 | 458 | Args: 459 | matrices: A tuple of 2 anaglyph matrices in the form of 460 | ((XR,XG,XB),(YR,YG,YB),(ZR,ZG,ZB)). 461 | ''' 462 | 463 | _METHODS = { 464 | "gray": 465 | ("lum", "lum"), 466 | "color": 467 | ("rgb", "rgb"), 468 | "half-color": 469 | ("lum", "rgb"), 470 | "wimmer": 471 | ("wim", "rgb") 472 | } 473 | 474 | _COLOR_SCHEMES = { 475 | "red-green": ( 476 | (1, 0, 0), (0, 1, 0)), 477 | "red-blue": ( 478 | (1, 0, 0), (0, 0, 1)), 479 | "red-cyan": ( 480 | (1, 0, 0), (0, 1, 1)), 481 | "green-magenta": ( 482 | (0, 1, 0), (1, 0, 1)), 483 | "amber-blue": ( 484 | (0.9, 1, 0), (0, 0, 0.7)), 485 | "magenta-cyan": ( 486 | (1, 0, 1), (0, 1, 1)) 487 | } 488 | 489 | _COLOR_MATRICES = { 490 | "rgb": ( 491 | (1, 0, 0), 492 | (0, 1, 0), 493 | (0, 0, 1) 494 | ), 495 | "wim": ( 496 | (0, 0.7, 0.3), 497 | (0.5, 0, 0.5), # ? 498 | (0.5, 0.5, 0) # ? 499 | ) 500 | } 501 | 502 | _DUBOIS = { 503 | "red-cyan": ( 504 | ((0.456, 0.500, 0.175), (-0.040, -0.038, -0.016), (-0.015, -0.021, -0.005)), 505 | ((-0.043, -0.088, -0.002), (0.378, 0.734, -0.018), (-0.072, -0.113, 1.226))), 506 | "green-magenta": ( 507 | ((-0.062, -0.158, -0.039), (0.284, 0.668, 0.143), (-0.015, -0.027, 0.021)), 508 | ((0.529, 0.705, 0.024), (-0.016, -0.015, -0.065), (0.009, 0.075, 0.937))), 509 | "amber-blue": ( 510 | ((1.062, -0.205, 0.299), (-0.026, 0.908, 0.068), (-0.038, -0.173, 0.022)), 511 | ((-0.016, -0.123, -0.017), (0.006, 0.062, -0.017), (0.094, 0.185, 0.911))) 512 | } 513 | 514 | def __init__(self, matrices): 515 | self.matrices = matrices 516 | 517 | @classmethod 518 | def _simple(cls, method_name, color_scheme, luma_coding=_DEFAULT_AG_LUMA): 519 | colors = cls._COLOR_SCHEMES[color_scheme] 520 | method = cls._METHODS[method_name] 521 | is_reversed = sum(colors[0]) > sum(colors[1]) 522 | if is_reversed: 523 | method = (method[1], method[0]) 524 | matrices = [] 525 | for matrix_name, color in zip(method, colors): 526 | matrix = [] 527 | if matrix_name == "lum": 528 | color_matrix = (luma_coding,)*3 529 | else: 530 | color_matrix = cls._COLOR_MATRICES[matrix_name] 531 | for color_band, intensity in zip(color_matrix, color): 532 | matrix.append(( 533 | color_band[0] * intensity, 534 | color_band[1] * intensity, 535 | color_band[2] * intensity)) 536 | matrices.append(tuple(matrix)) 537 | 538 | obj = cls(matrices) 539 | obj.is_reversed = is_reversed 540 | obj.colors = colors 541 | return obj 542 | 543 | @classmethod 544 | def gray(cls, color_scheme=_DEFAULT_AG_CS, 545 | luma_coding=_DEFAULT_AG_LUMA): 546 | '''The gray anaglyph method 547 | 548 | Args: 549 | color_scheme: The color scheme. 550 | luma_coding: The luma coding. 551 | ''' 552 | return cls._simple("gray", color_scheme, luma_coding) 553 | 554 | @classmethod 555 | def color(cls, color_scheme=_DEFAULT_AG_CS): 556 | '''The color anaglyph method 557 | 558 | Args: 559 | color_scheme: The color scheme. 560 | ''' 561 | return cls._simple("color", color_scheme) 562 | 563 | @classmethod 564 | def halfColor(cls, color_scheme=_DEFAULT_AG_CS, 565 | luma_coding=_DEFAULT_AG_LUMA): 566 | '''The half color anaglyph method 567 | 568 | Args: 569 | color_scheme: The color scheme. 570 | luma_coding: The luma coding. 571 | ''' 572 | return cls._simple("half-color", color_scheme, luma_coding) 573 | 574 | @classmethod 575 | def wimmer(cls, color_scheme=_DEFAULT_AG_CS): 576 | '''The wimmer anaglyph method 577 | 578 | Args: 579 | color_scheme: The color scheme. 580 | ''' 581 | obj = cls._simple("wimmer", color_scheme) 582 | if color_scheme == "red-cyan": 583 | obj.process_images = obj._process_images_wimmer 584 | obj.process_expression = obj._process_expression_wimmer 585 | return obj 586 | 587 | def _process_images_wimmer(self, images): 588 | left = images[0].copy() 589 | right = images[1].copy() 590 | 591 | for i in left.load(), right.load(): 592 | for y in range(left.height): 593 | for x in range(left.width): 594 | c = list(i[x, y]) 595 | 596 | if c[0] > c[1] and c[0] > c[1]: 597 | c[1] = int(round(c[0]*0.3+c[1]*0.7)) 598 | c[2] = int(round(c[0]*0.3+c[2]*0.7)) 599 | 600 | i[x, y] = tuple(c) 601 | return left, right 602 | 603 | def _process_expression_wimmer(self, band_i, expression): 604 | if self.colors[self.is_reversed][band_i]: 605 | return ("((" + expression + "/255)**(1/" + 606 | str(1 + (0.3 * self.colors[self.is_reversed][band_i])) + 607 | "))*255") 608 | return expression 609 | 610 | @classmethod 611 | def dubois(cls, color_scheme=_DEFAULT_AG_CS): 612 | '''The dubois anaglyph method 613 | 614 | Args: 615 | color_scheme: The color scheme. 616 | ''' 617 | return cls(cls._DUBOIS[color_scheme]) 618 | 619 | 620 | def process_images(self, images): 621 | '''Process the initial images 622 | 623 | You may override this method in a subclass. Without an override, 624 | this method simply passes through the images. 625 | 626 | This gets called at the start of the anaglyph creation. It takes 627 | and returns the images to be turned into an anaglyph image. 628 | It is best to use the image copy method to make sure not to 629 | manipulate the original input images. 630 | 631 | Args: 632 | images: 633 | The two PIL images to be turned into an anaglyph image. 634 | 635 | Returns: 636 | The processed images. 637 | ''' 638 | return images 639 | 640 | def process_expression(self, band_i, expression): 641 | '''Process the image expression 642 | 643 | You may override this method in a subclass. Without an override, 644 | this method simply passes throught the expression. 645 | 646 | This gets called for each color band of the 2 images: red, green 647 | and blue. It takes and returns the image expression used to 648 | create the anaglyph image. This expression is used by the Pillow 649 | PIL.ImageMath.eval method and its syntax is explained in its 650 | documentation. 651 | 652 | Args: 653 | band_i: 654 | The band index starting from 0 for red, green and blue. 655 | expression: The image expression. 656 | 657 | Returns: 658 | The processed expression. 659 | ''' 660 | return expression 661 | 662 | def createAnaglyph(self, images): 663 | '''Create an anaglyph image from two images. 664 | 665 | Args: 666 | images: Two PIL images. 667 | 668 | Returns: 669 | The anaglyph PIL image. 670 | ''' 671 | left, right = self.process_images(images) 672 | 673 | left_bands = left.split() 674 | right_bands = right.split() 675 | output_bands = list() 676 | for i in range(3): 677 | expression = ( 678 | "(float(lr)*{lm[0]}+float(lg)*{lm[1]}+float(lb)*{lm[2]}+" + 679 | "float(rr)*{rm[0]}+float(rg)*{rm[1]}+float(rb)*{rm[2]})" 680 | ).format(lm=self.matrices[0][i], rm=self.matrices[1][i]) 681 | 682 | expression = self.process_expression(i, expression) 683 | 684 | output_bands.append( 685 | ImageMath.eval("convert(" + expression + ", 'L')", 686 | lr=left_bands[0], lg=left_bands[1], lb=left_bands[2], 687 | rr=right_bands[0], rg=right_bands[1], rb=right_bands[2])) 688 | 689 | if len(left_bands) > 3 and len(right_bands) > 3: 690 | output_bands.append( 691 | ImageChops.lighter(left_bands[3], right_bands[3])) 692 | return Image.merge("RGBA", output_bands) 693 | return Image.merge("RGB", output_bands) 694 | 695 | def create_anaglyph(images, method="wimmer", 696 | color_scheme=_DEFAULT_AG_CS, luma_coding=_DEFAULT_AG_LUMA): 697 | """Create an anaglyph image from two images. 698 | 699 | This is a convenience function for the AnaglyphMethod class. 700 | 701 | Args: 702 | images: Two PIL images. 703 | method: The anaglyph method. 704 | The available methods are gray, color, half-color, 705 | wimmer and dubois. 706 | color_scheme: The anaglyph color scheme. 707 | The non-complementary colors of the color schemes are mainly 708 | to be used with the gray method. 709 | The available color schemes are red-green, red-blue, 710 | red-cyan, green-magenta, amber-blue and magenta-cyan. 711 | luma_coding: 712 | The luma coding for the gray and half-color methods. 713 | 714 | Returns: 715 | The anaglyph PIL image. 716 | """ 717 | if method == "gray": 718 | am = AnaglyphMethod.gray(color_scheme, luma_coding) 719 | elif method == "color": 720 | am = AnaglyphMethod.color(color_scheme) 721 | elif method == "half-color": 722 | am = AnaglyphMethod.halfColor(color_scheme, luma_coding) 723 | elif method == "wimmer": 724 | am = AnaglyphMethod.wimmer(color_scheme) 725 | elif method == "dubois": 726 | am = AnaglyphMethod.dubois(color_scheme) 727 | 728 | return am.createAnaglyph(images) 729 | 730 | PATTERN_CHECKERBOARD = 0 731 | PATTERN_INTERLACED_H = 1 732 | PATTERN_INTERLACED_V = 2 733 | 734 | def create_patterned_image(images, 735 | pattern=PATTERN_INTERLACED_H, width=1, left_is_even=True): 736 | """Create a patterned image from two images. 737 | 738 | Args: 739 | images: Two PIL images. 740 | pattern: the pattern number. 741 | width: the width of a line/square. 742 | left_is_even: Set the first image to be the even line/square. 743 | 744 | Returns: 745 | The patterned PIL image. 746 | """ 747 | output = images[0].copy() 748 | o = output.load() 749 | r = images[1].load() 750 | 751 | is_even = True 752 | two_width = width * 2 753 | for y in range(output.height): 754 | for x in range(output.width): 755 | if pattern == PATTERN_INTERLACED_H: 756 | is_even = (y % two_width) < width 757 | elif pattern == PATTERN_INTERLACED_V: 758 | is_even = (x % two_width) < width 759 | elif pattern == PATTERN_CHECKERBOARD: 760 | is_even = (((y % two_width) < width) == 761 | ((x % two_width) < width)) 762 | if is_even != left_is_even: 763 | o[x,y] = r[x,y] 764 | return output 765 | 766 | def save_as_wiggle_gif_image(output_file, images, total_duration=200): 767 | """Save multiple images as a wiggle GIF image. 768 | 769 | Args: 770 | output_file: The file name of the output GIF file. 771 | images: Multiple PIL images. 772 | total_duration: The total duration for all the images to be 773 | shown before looping. 774 | """ 775 | images[0].save(output_file, format="gif", save_all=True, loop=0, 776 | duration=int(round(total_duration/len(images))), 777 | append_images=images[1:] + list(reversed(images[1:-1]))) 778 | 779 | def save_as_mpo_image(output_file, images): 780 | """Save multiple images as a MPO image. 781 | For a stereoscopic MPO image file, input the left and right images. 782 | 783 | Args: 784 | output_file: The file name of the output MPO file. 785 | images: Multiple PIL images. 786 | """ 787 | images[0].save(output_file, format='mpo', save_all=True, 788 | append_images=images[1:]) 789 | 790 | def _main(): 791 | import sys 792 | import argparse 793 | import io 794 | from PIL import ImageOps, ImageSequence 795 | 796 | parser = argparse.ArgumentParser( 797 | description="Convert 2 images into a stereoscopic 3D image", 798 | usage="%(prog)s [OPTION]... [IN] [IN2] [OUT] [OUT2]") 799 | 800 | parser.add_argument("image_in", 801 | metavar="IN", type=str, nargs='?', 802 | help="left input image or an MPO input file. If omitted or set to a " 803 | "single dash (\"-\"), an MPO is read from STDIN") 804 | parser.add_argument("image_in2", 805 | metavar="IN2", type=str, nargs='?', 806 | help="right input image. Set this to a single dash (\"-\") for " 807 | "setting the output arguments when inputting from STDIN or " 808 | "reading an MPO file") 809 | parser.add_argument("image_output", 810 | metavar="OUT", type=str, nargs='?', 811 | help="output file. If left omitted, output to STDOUT. If outputting " 812 | "to STDOUT or the file extension is omitted, the output format " 813 | "argument is required") 814 | parser.add_argument("image_output2", 815 | metavar="OUT2", type=str, nargs='?', 816 | help="output an optional second image for split left and right") 817 | 818 | parser.add_argument("-q", "--quality", 819 | dest='quality', metavar="VALUE", type=int, default="95", 820 | help="set the output image quality: 1-100 [default: %(default)s]") 821 | parser.add_argument("-f", "--format", 822 | dest='format', metavar="FORMAT", type=str, 823 | help="set the output image format: JPG, PNG, GIF, MPO,... " 824 | "If left omitted, the format to use is determined from " 825 | "the filename extension") 826 | parser.add_argument("--bg", 827 | dest='bg_color', type=int, nargs=4, 828 | metavar=("RED", "GREEN", "BLUE", "ALPHA"), default=None, 829 | help="set the background color and transparency (alpha): 0-255 each. " 830 | "This is also the color for the divider and border") 831 | parser.add_argument("--border", 832 | dest='border', metavar="WIDTH", type=int, default=0, 833 | help="surround the output image with a border of a given width") 834 | 835 | group = parser.add_argument_group('Side-by-side') 836 | group.add_argument("-x", "--cross-eye", 837 | dest='cross_eye', action='store_true', 838 | help="output an image for cross-eyed viewing, right/left") 839 | group.add_argument("-p", "--parallel", 840 | dest='parallel', action='store_true', 841 | help="output an image for parallel viewing, left/right") 842 | group.add_argument("-o", "--over-under", 843 | dest='over_under', action='store_true', 844 | help="output an over/under image, left is over") 845 | group.add_argument("-u", "--under-over", 846 | dest='under_over', action='store_true', 847 | help="output an under/over image, left is under") 848 | 849 | group.add_argument("-s", "--squash", 850 | dest='squash', action='store_true', 851 | help="squash the sides to be half their width (cross-eye, parallel) " 852 | "or height (over/under, under/over)") 853 | group.add_argument("--div", 854 | dest='divider', metavar="WIDTH", type=int, default=0, 855 | help="separate the two sides with a divider of a given width") 856 | 857 | group = parser.add_argument_group('Anaglyph') 858 | group.add_argument("-a", "--anaglyph", 859 | dest='anaglyph', action='store_true', 860 | help="output an anaglyph image") 861 | group.add_argument("-m", "--anaglyph-method", 862 | dest='anaglyph_method', metavar="METHOD", type=str, default="wimmer", 863 | help="set the anaglyph method: " 864 | "gray, color, half-color, wimmer, dubois [default: %(default)s]. " 865 | "The dubois method is only available with the " 866 | "red-cyan, green-magenta and amber-blue color schemes") 867 | group.add_argument("--cs", "--color-scheme", 868 | dest='color_scheme', metavar="SCHEME", type=str, default="red-cyan", 869 | help="set the anaglyph color scheme: " 870 | "red-green, red-blue, red-cyan, green-magenta, amber-blue, " 871 | "magenta-cyan [default: %(default)s]. " 872 | "The non-complementary colors are mainly to be used with the " 873 | "gray method") 874 | group.add_argument("--lc", "--luma-coding", 875 | dest='luma_coding', metavar="CODING", type=str, default="rec709", 876 | help="set the luma coding " 877 | "for the anaglyph gray and half-color methods: " 878 | "rgb, rec601 (PAL/NTSC), rec709 (HDTV) [default: %(default)s]") 879 | 880 | group = parser.add_argument_group('Animated') 881 | group.add_argument("-w", "--wiggle", 882 | dest='wiggle', action='store_true', 883 | help="output a wiggle GIF image") 884 | group.add_argument("-t", "--duration", 885 | dest='duration', metavar="DURATION", type=int, default=300, 886 | help="set the total duration of the wiggle GIF animation " 887 | "in milliseconds [default: %(default)s]") 888 | 889 | group = parser.add_argument_group('Patterned') 890 | group.add_argument("--ih", "--interlaced-h", 891 | dest='interlaced_horizontal', action='store_true', 892 | help="output a horizontally interlaced image") 893 | group.add_argument("--iv", "--interlaced-v", 894 | dest='interlaced_vertical', action='store_true', 895 | help="outout a vertically interlaced image") 896 | group.add_argument("--cb", "--checkerboard", 897 | dest='checkerboard', action='store_true', 898 | help="output a checkerboard patterned image") 899 | group.add_argument("--odd", 900 | dest='odd', action='store_true', 901 | help="set the left image to be the odd line/square of the pattern " 902 | "instead of the even one") 903 | group.add_argument("--pw", "--pattern-width", 904 | dest='pattern_width', metavar="WIDTH", type=int, default=1, 905 | help="set the width of a line/square " 906 | "of the pattern [default: %(default)s]") 907 | 908 | group = parser.add_argument_group('Preprocessing') 909 | if "cv2" in sys.modules and "numpy" in sys.modules: 910 | group.add_argument("-A", "--auto-align", 911 | dest='auto_align', action='store_true', 912 | help="auto align the right image to the left image. " 913 | "The aspect ratio is preserved") 914 | 915 | group.add_argument("-T", "--rotate", 916 | dest='rotate', type=float, nargs=2, 917 | metavar=("LEFT", "RIGHT"), default=(0, 0), 918 | help="rotate both images in degrees counter clockwise. " 919 | "The aspect ratio is preserved") 920 | group.add_argument("-S", "--shift", 921 | dest='shift', type=float, nargs=2, 922 | metavar=("X", "Y"), default=(0, 0), 923 | help="shift the right image in relation to the left image. " 924 | "The aspect ratio is preserved") 925 | group.add_argument("-X", "--expand", 926 | dest='expand', action='store_true', 927 | help="set to expand the images around the aligned/rotated pictures. " 928 | "The default is to shrink the images into the pictures, " 929 | "excluding the empty and non-overlapping areas") 930 | 931 | group.add_argument("-C", "--crop", 932 | dest='crop', type=str, nargs=4, 933 | metavar=("LEFT", "TOP", "RIGHT", "BOTTOM"), default=(0, 0, 0, 0), 934 | help="crop both images in either pixels or percentage") 935 | 936 | group.add_argument("-R", "--resize", 937 | dest='resize', type=int, nargs=2, 938 | metavar=("WIDTH", "HEIGHT"), default=(0, 0), 939 | help="resize both images to WIDTHxHEIGHT. " 940 | "The dimension with a value of 0 is calculated automatically " 941 | "to preserve the aspect ratio") 942 | group.add_argument("-O", "--offset", 943 | dest='offset', type=str, default="50%", 944 | help="set the resize offset from top or left " 945 | "in either pixels or percentage [default: %(default)s]") 946 | 947 | args = parser.parse_args() 948 | 949 | if args.image_output: 950 | image_output = args.image_output 951 | else: 952 | if args.format is None and not args.wiggle: 953 | print("Either specify the output file name or the format " 954 | "to be used for outputting to STDOUT.", file=sys.stderr) 955 | exit() 956 | image_output = sys.stdout.buffer 957 | 958 | if not args.image_in2 or args.image_in2 == "-": 959 | if not args.image_in or args.image_in == "-": 960 | image_in = io.BytesIO(sys.stdin.buffer.read()) 961 | else: 962 | image_in = args.image_in 963 | multiframe_image = Image.open(image_in) 964 | images = ImageSequence.all_frames(multiframe_image) 965 | else: 966 | images = [Image.open(args.image_in), Image.open(args.image_in2)] 967 | 968 | for i in range(len(images)): 969 | images[i] = fix_orientation(images[i]) 970 | 971 | if images[i].mode not in ("RGB", "RGBA"): 972 | images[i] = images[i].convert("RGBA") 973 | 974 | if i > 0 and images[0].size != images[i].size: 975 | print("Given images are not the same size!", file=sys.stderr) 976 | exit() 977 | 978 | if any(args.shift) or any(args.rotate) or args.auto_align: 979 | if args.auto_align: 980 | matrices = find_alignments(images) 981 | else: 982 | matrices = [((1, 0, 0), (0, 1, 0), (0, 0, 1))]*2 983 | 984 | for i in range(2): 985 | if i == 0: 986 | xy = -args.shift[0], -args.shift[1] 987 | else: 988 | xy = args.shift 989 | 990 | matrix = xy_and_angle_to_matrix(xy, args.rotate[i], images[i].size) 991 | matrices[i] = combine_matrices(matrices[i], matrix) 992 | 993 | images = transform(images, matrices, not args.expand) 994 | 995 | for i in range(len(images)): 996 | if any(args.crop): 997 | images[i] = crop(images[i], args.crop) 998 | 999 | if any(args.resize): 1000 | images[i] = resize(images[i], args.resize, args.offset) 1001 | 1002 | is_format_mpo = ((args.format and args.format.lower() == "mpo") 1003 | or image_output.rsplit(".", 1)[-1].lower() == "mpo") 1004 | 1005 | do_save = True 1006 | if args.anaglyph: 1007 | if args.luma_coding == "rgb": 1008 | luma_coding = ANAGLYPH_LUMA_RGB 1009 | elif args.luma_coding == "rec601": 1010 | luma_coding = ANAGLYPH_LUMA_REC601 1011 | elif args.luma_coding == "rec709": 1012 | luma_coding = ANAGLYPH_LUMA_REC709 1013 | images = [create_anaglyph( 1014 | images, args.anaglyph_method, args.color_scheme, luma_coding)] 1015 | elif args.interlaced_horizontal: 1016 | images = [create_patterned_image( 1017 | images, PATTERN_INTERLACED_H, args.pattern_width, not args.odd)] 1018 | elif args.interlaced_vertical: 1019 | images = [create_patterned_image( 1020 | images, PATTERN_INTERLACED_V, args.pattern_width, not args.odd)] 1021 | elif args.checkerboard: 1022 | images = [create_patterned_image( 1023 | images, PATTERN_CHECKERBOARD, args.pattern_width, not args.odd)] 1024 | elif args.wiggle or is_format_mpo: 1025 | do_save = False 1026 | else: 1027 | if not (args.cross_eye or args.parallel or 1028 | args.over_under or args.under_over): 1029 | args.cross_eye = True 1030 | 1031 | is_horizontal = args.cross_eye or args.parallel 1032 | 1033 | if args.squash: 1034 | for i in range(len(images)): 1035 | images[i] = squash(images[i], is_horizontal) 1036 | 1037 | if args.cross_eye or args.under_over: 1038 | images.reverse() 1039 | 1040 | if args.image_output2 is None: 1041 | images = [create_side_by_side_image( 1042 | images, is_horizontal, args.divider)] 1043 | 1044 | for i in range(len(images)): 1045 | if args.border: 1046 | images[i] = ImageOps.expand(images[i], args.border) 1047 | 1048 | if args.bg_color and images[i].mode == "RGBA": 1049 | background_image = Image.new( 1050 | "RGBA", images[i].size, tuple(args.bg_color)) 1051 | images[i] = Image.alpha_composite(background_image, images[i]) 1052 | 1053 | if do_save: 1054 | try: 1055 | path = (image_output, args.image_output2)[i] 1056 | except: 1057 | break 1058 | try: 1059 | images[i].save(path, 1060 | format=args.format, quality=args.quality, optimize=True) 1061 | except OSError: 1062 | images[i].convert("RGB").save(path, 1063 | format=args.format, quality=args.quality, optimize=True) 1064 | 1065 | if args.wiggle: 1066 | save_as_wiggle_gif_image(image_output, images, args.duration) 1067 | elif is_format_mpo: 1068 | save_as_mpo_image(image_output, images) 1069 | 1070 | if __name__ == "__main__": 1071 | _main() 1072 | --------------------------------------------------------------------------------