Skip to content

Commit

Permalink
refactor: Removed loguru
Browse files Browse the repository at this point in the history
Loguru threw runtime exception on Windows in #11
  • Loading branch information
dilawar committed Jul 8, 2022
1 parent 00e5c41 commit 8bc49f9
Show file tree
Hide file tree
Showing 11 changed files with 28 additions and 68 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
strategy:
matrix:
os: [ ubuntu-latest, macos-latest ]
python-version: ['3.7', '3.9']
python-version: ['3.7', '3.9', '3.10']

steps:
- uses: actions/checkout@v2
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# [0.2.3] 2022-07-08

- Removed loguru. #11

# 2021-06-30: v0.2.2

- Fixed regression: axis transformation was broken.
Expand Down
Binary file modified figures/ECGImage.result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified figures/graph_with_grid.result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified figures/graphs_1.result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified figures/trimmed.result.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions plotdigitizer/locate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
__email__ = "[email protected]"

from pathlib import Path
from loguru import logger
import logging
import numpy as np
import math
import cv2
Expand All @@ -17,7 +17,7 @@
def _locate_points(k, x, y, s, p):
global img_
if k == 4:
logger.info(f"You clicked on {x}/{y}")
logging.info(f"You clicked on {x}/{y}")
_add_point(x, y)


Expand Down Expand Up @@ -60,7 +60,7 @@ def _add_axis(img):

def locate(imgfile: Path):
global img_
logger.info(f"Loading {imgfile}")
logging.info(f"Loading {imgfile}")
assert imgfile.is_file(), f"{imgfile} does not exists or could not be read"
cv2.namedWindow(WINDOW_NAME)
cv2.setMouseCallback(WINDOW_NAME, _locate_points)
Expand Down
41 changes: 14 additions & 27 deletions plotdigitizer/plotdigitizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,7 @@
# Logger
#
import sys
from loguru import logger

logger.remove()
logger.add(sys.stderr, level="WARNING")

logger.add(
Path(tempfile.gettempdir()) / "plotdigitizer.log", level="DEBUG", rotation="10MB"
)
import logging

WindowName_ = "PlotDigitizer"
ix_, iy_ = 0, 0
Expand Down Expand Up @@ -58,7 +51,7 @@ def save_img_in_cache(img: np.ndarray, filename: T.Optional[T.Union[Path, str]]
filename = Path(f"{data_to_hash(img)}.png")
outpath = cache() / filename
cv.imwrite(str(outpath), img)
logger.debug(f" Saved to {outpath}")
logging.debug(f" Saved to {outpath}")


def plot_traj(traj, outfile: Path):
Expand All @@ -84,7 +77,7 @@ def plot_traj(traj, outfile: Path):
plt.show()
else:
plt.savefig(outfile)
logger.info(f"Saved to {outfile}")
logging.info(f"Saved to {outfile}")
plt.close()


Expand All @@ -94,7 +87,7 @@ def click_points(event, x, y, flags, params):
# Function to record the clicks.
YROWS = img_.shape[0]
if event == cv.EVENT_LBUTTONDOWN:
logger.info(f"You clicked on {(x, YROWS-y)}")
logging.info(f"You clicked on {(x, YROWS-y)}")
locations_.append(geometry.Point(x, YROWS - y))


Expand All @@ -120,7 +113,7 @@ def ask_user_to_locate_points(points, img):
key = cv.waitKey(1) & 0xFF
if key == "q":
break
logger.info("You clicked %s" % locations_)
logging.info("You clicked %s" % locations_)


def list_to_points(points) -> T.List[geometry.Point]:
Expand Down Expand Up @@ -148,10 +141,10 @@ def transform_axis(img, erase_near_axis: int = 0):
T = axis_transformation(points_, locations_)
p = geometry.find_origin(locations_)
offCols, offRows = p.x, p.y
logger.info(f"{locations_} → origin {offCols}, {offRows}")
logging.info(f"{locations_} → origin {offCols}, {offRows}")
img[:, : offCols + erase_near_axis] = params_["background"]
img[-offRows - erase_near_axis :, :] = params_["background"]
logger.debug(f"Tranformation params: {T}")
logging.debug(f"Tranformation params: {T}")
return T


Expand Down Expand Up @@ -184,7 +177,7 @@ def _find_trajectory_colors(img, plot: bool = False) -> T.Tuple[int, T.List[int]

# we assume that bgcolor is close to white.
if bgcolor < 128:
logger.error(
logging.error(
"I computed that background is 'dark' which is unacceptable to me."
)
quit(-1)
Expand All @@ -203,7 +196,7 @@ def compute_foregrond_background_stats(img) -> T.Dict[str, float]:
bgcolor, trajcolors = _find_trajectory_colors(img)
params["background"] = bgcolor
params["timeseries_colors"] = trajcolors
logger.info(f" computed parameters: {params}")
logging.info(f" computed parameters: {params}")
return params


Expand All @@ -214,7 +207,7 @@ def process_image(img):

T = transform_axis(img, erase_near_axis=3)
assert img.std() > 0.0, "No data in image"
# logger.info(f" {img.mean()} {img.std()}")
# logging.info(f" {img.mean()} {img.std()}")
save_img_in_cache(img, f"{args_.INPUT.name}.transformed_axis.png")

# extract the plot that has color which is farthest from the background.
Expand All @@ -231,7 +224,7 @@ def run(args):

infile = Path(args.INPUT)
assert infile.exists(), f"{infile} does not exists."
logger.info(f"Extracting trajectories from {infile}")
logging.info(f"Extracting trajectories from {infile}")

img_ = cv.imread(str(infile), 0)

Expand All @@ -246,10 +239,10 @@ def run(args):

points_ = list_to_points(args.data_point)
locations_ = list_to_points(args.location)
logger.debug(f"data points {args.data_point} → location on image {args.location}")
logging.debug(f"data points {args.data_point} → location on image {args.location}")

if len(locations_) != len(points_):
logger.warning(
logging.warning(
"Either the location of data-points are not specified or their numbers don't"
" match with given datapoints. Asking user..."
)
Expand All @@ -275,7 +268,7 @@ def run(args):
with open(outfile, "w") as f:
for r in traj:
f.write("%g %g\n" % (r))
logger.info("Wrote trajectory to %s" % outfile)
logging.info("Wrote trajectory to %s" % outfile)


def main():
Expand Down Expand Up @@ -324,12 +317,6 @@ def main():
action="store_true",
help="Preprocess the image. Useful with bad resolution images.",
)
parser.add_argument(
"--debug",
required=False,
action="store_true",
help="Enable debug logger",
)
args = parser.parse_args()
run(args)

Expand Down
8 changes: 3 additions & 5 deletions plotdigitizer/trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@

import numpy as np
import cv2 as cv

from collections import defaultdict

from loguru import logger
import logging


def _find_center(vec):
Expand All @@ -19,7 +17,7 @@ def fit_trajectory_using_median(traj, T, img):
r, _ = img.shape

# x, y = zip(*sorted(traj.items()))
# logger.info((xvec, ys))
# logging.info((xvec, ys))

for k in sorted(traj):
x = k
Expand Down Expand Up @@ -54,7 +52,7 @@ def _valid_px(val: int) -> int:


def find_trajectory(img: np.ndarray, pixel: int, T):
logger.info(f"Extracting trajectory for color {pixel}")
logging.info(f"Extracting trajectory for color {pixel}")
assert img.min() <= pixel <= img.max(), f"{pixel} is outside the range"

# Find all pixels which belongs to a trajectory.
Expand Down
32 changes: 2 additions & 30 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "plotdigitizer"
version = "0.2.2"
version = "0.2.3"
description = "Extract raw data from plots images"
authors = ["Dilawar Singh <[email protected]>"]
maintainers = ["Dilawar Singh <[email protected]>"]
Expand All @@ -13,7 +13,6 @@ python = "^3.7"
opencv-python = "^4.5.1"
numpy = "^1.19.5"
matplotlib = "^3.3.4"
loguru = "^0.5.3"

[tool.poetry.dev-dependencies]
pytest = "^6.2.2"
Expand Down

0 comments on commit 8bc49f9

Please sign in to comment.