Skip to content

Instantly share code, notes, and snippets.

@noureddin
Last active August 11, 2018 01:07
Show Gist options
  • Save noureddin/7826804116861e3195511330cfecccce to your computer and use it in GitHub Desktop.
Save noureddin/7826804116861e3195511330cfecccce to your computer and use it in GitHub Desktop.
using svd to “compress” an image, using opencv and numpy
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# do a lossy compression to an image using Single-value Decomposition (SVD)
# using numpy and opencv (and python)
import numpy as np
import cv2
from sys import argv
# give an image as an argument to this script,
# or put an image named img.jpg in the same folder as the script.
image_file = argv[1] if len(argv) > 1 else 'img.jpg'
# hotkeys:
# - Esc or q: quit
# - Space: toggle original/compressed
# - j: reduce the number of single values used
# - k: increase the number of single values used
img = cv2.imread(image_file, 0) # 0 means grayscale
u, s, vh = np.linalg.svd(img)
ns = s.shape[0] # number of single values
cv2.namedWindow('svd')
cv2.createTrackbar('Original or Truncated', 'svd', 1, 1, lambda *args: None)
cv2.createTrackbar('New Rank', 'svd', 1, ns, lambda *args: None)
while True:
n = cv2.getTrackbarPos('New Rank', 'svd')
newimg = np.clip(
np.dot(u[:, :n] * s[:n], vh[:n, :]),
0, 255
).astype('uint8')
want_truncated = cv2.getTrackbarPos('Original or Truncated', 'svd')
if want_truncated:
cv2.imshow('svd', newimg)
else:
cv2.imshow('svd', img)
key = cv2.waitKey(1) & 0xff
if key in (27, ord('q')): # ESC or q
break
elif key == ord('j'):
cv2.setTrackbarPos('New Rank', 'svd', n-1)
elif key == ord('k'):
cv2.setTrackbarPos('New Rank', 'svd', n+1)
elif key == ord(' '):
cv2.setTrackbarPos('Original or Truncated', 'svd', 1-want_truncated)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment