﻿ 机器学习实战：用SVD压缩图像 - 鸿网互联

# 机器学习实战：用SVD压缩图像

Learn by doing

https://huggingface.co/spaces/beihai/Image-Compression-with-SVD

https://huggingface.co/spaces/beihai/Image-Compression-with-SVD

p表示奇异值的百分比，根据指定的清晰度提取奇异值清晰度越高，压缩比越低，提取的奇异值的个数也就越多，图片也就越不会失真）

def rebuild_img(u, sigma, v, percent):
m = len(u)
n = len(v)
a = np.zeros((m, n))

count = (int)(sum(sigma))
curSum = 0
k = 0
while curSum <= count * percent:
uk = u[:, k].reshape(m, 1)
vk = v[k].reshape(1, n)
a += sigma[k] * np.dot(uk, vk)
curSum += sigma[k]
k += 1

a[a < 0] = 0
a[a > 255] = 255

import os
import cv2
import numpy as np
from func import rebuild_img

def inference(img,k):
u, sigma, v = np.linalg.svd(input_img[:, :, 0])
R = rebuild_img(u, sigma, v, k)
u, sigma, v = np.linalg.svd(input_img[:, :, 1])
G = rebuild_img(u, sigma, v, k)
u, sigma, v = np.linalg.svd(input_img[:, :, 2])
B = rebuild_img(u, sigma, v, k)
restored_img = np.stack((R, G, B), 2)
return Image.fromarray(restored_img[:, :, ::-1])

gr.Interface(
inference,
[
gr.inputs.Image(type="filepath", label="Input"),gr.inputs.Slider(0, 1, 0.1,default=0.6,label= 'Compression ratio')],
gr.outputs.Image(type="pil", label="Output"),
title=title,
description=description,
article=article
).launch(enable_queue=True,cache_examples=True,share=True)

File "/home/user/.local/lib/python3.8/site-packages/cv2/__init__.py", line 8, in <module>
from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

1 yum安装：

yum install libglvnd-glx

2 重新安装opencv包：

pip uninstall opencv-python