Spaces:
Running
Running
File size: 7,229 Bytes
a62d4c5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
// @ts-nocheck
/* eslint-disable camelcase */
/* eslint-disable no-plusplus */
import cv, { Mat } from 'opencv-ts'
import { ensureModel } from './cache'
import { getCapabilities } from './util'
import type { modelType } from './cache'
// ort.env.debug = true
// ort.env.logLevel = 'verbose'
// ort.env.webgpu.profilingMode = 'default'
function loadImage(url: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image()
img.crossOrigin = 'Anonymous'
img.onload = () => resolve(img)
img.onerror = () => reject(new Error(`Failed to load image from ${url}`))
img.src = url
})
}
function imgProcess(img: Mat) {
const channels = new cv.MatVector()
cv.split(img, channels) // 分割通道
const C = channels.size() // 通道数
const H = img.rows // 图像高度
const W = img.cols // 图像宽度
const chwArray = new Uint8Array(C * H * W) // 创建新的数组来存储转换后的数据
for (let c = 0; c < C; c++) {
const channelData = channels.get(c).data // 获取单个通道的数据
for (let h = 0; h < H; h++) {
for (let w = 0; w < W; w++) {
chwArray[c * H * W + h * W + w] = channelData[h * W + w]
// chwArray[c * H * W + h * W + w] = channelData[h * W + w]
}
}
}
channels.delete() // 清理内存
return chwArray // 返回转换后的数据
}
function markProcess(img: Mat) {
const channels = new cv.MatVector()
cv.split(img, channels) // 分割通道
const C = 1 // 通道数
const H = img.rows // 图像高度
const W = img.cols // 图像宽度
const chwArray = new Uint8Array(C * H * W) // 创建新的数组来存储转换后的数据
for (let c = 0; c < C; c++) {
const channelData = channels.get(0).data // 获取单个通道的数据
for (let h = 0; h < H; h++) {
for (let w = 0; w < W; w++) {
chwArray[c * H * W + h * W + w] = (channelData[h * W + w] !== 255) * 255
}
}
}
channels.delete() // 清理内存
return chwArray // 返回转换后的数据
}
function processImage(
img: HTMLImageElement,
canvasId?: string
): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
try {
const src = cv.imread(img)
const src_rgb = new cv.Mat()
// 将图像从RGBA转换为RGB
cv.cvtColor(src, src_rgb, cv.COLOR_RGBA2RGB)
if (canvasId) {
cv.imshow(canvasId, src_rgb)
}
resolve(imgProcess(src_rgb))
src.delete()
src_rgb.delete()
} catch (error) {
reject(error)
}
})
}
function processMark(
img: HTMLImageElement,
canvasId?: string
): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
try {
const src = cv.imread(img)
const src_grey = new cv.Mat()
// 将图像从RGBA转换为二值化
cv.cvtColor(src, src_grey, cv.COLOR_BGR2GRAY)
if (canvasId) {
cv.imshow(canvasId, src_grey)
}
resolve(markProcess(src_grey))
src.delete()
} catch (error) {
reject(error)
}
})
}
function postProcess(uint8Data: Uint8Array, width: number, height: number) {
const chwToHwcData = []
const size = width * height
for (let h = 0; h < height; h++) {
for (let w = 0; w < width; w++) {
for (let c = 0; c < 3; c++) {
// RGB通道
const chwIndex = c * size + h * width + w
const pixelVal = uint8Data[chwIndex]
let newPiex = pixelVal
if (pixelVal > 255) {
newPiex = 255
} else if (pixelVal < 0) {
newPiex = 0
}
chwToHwcData.push(newPiex) // 归一化反转
}
chwToHwcData.push(255) // Alpha通道
}
}
return chwToHwcData
}
function imageDataToDataURL(imageData) {
// 创建 canvas
const canvas = document.createElement('canvas')
canvas.width = imageData.width
canvas.height = imageData.height
// 绘制 imageData 到 canvas
const ctx = canvas.getContext('2d')
ctx.putImageData(imageData, 0, 0)
// 导出为数据 URL
return canvas.toDataURL()
}
function configEnv(capabilities) {
ort.env.wasm.wasmPaths =
'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.16.3/dist/'
if (capabilities.webgpu) {
ort.env.wasm.numThreads = 1
} else {
if (capabilities.threads) {
ort.env.wasm.numThreads = navigator.hardwareConcurrency ?? 4
}
if (capabilities.simd) {
ort.env.wasm.simd = true
}
ort.env.wasm.proxy = true
}
console.log('env', ort.env.wasm)
}
const resizeMark = (
image: HTMLImageElement,
width: number,
height: number
): Promise<HTMLImageElement> => {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
// 将图片绘制到canvas上,并调整大小
const ctx = canvas.getContext('2d')
if (!ctx) {
reject(new Error('Unable to get canvas context'))
return
}
ctx.drawImage(image, 0, 0, width, height)
// 获取调整大小后的图片URL
const resizedImageUrl = canvas.toDataURL()
// 创建一个新的Image对象并设置其src为调整大小后的图片URL
const resizedImage = new Image()
resizedImage.onload = () => resolve(resizedImage)
resizedImage.onerror = () =>
reject(new Error('Failed to load resized image'))
resizedImage.src = resizedImageUrl
})
}
let model: ArrayBuffer | null = null
export default async function inpaint(
imageFile: File | HTMLImageElement,
maskBase64: string
) {
console.time('sessionCreate')
if (!model) {
const capabilities = await getCapabilities()
configEnv(capabilities)
const modelBuffer = await ensureModel('inpaint')
model = await ort.InferenceSession.create(modelBuffer, {
executionProviders: [capabilities.webgpu ? 'webgpu' : 'wasm'],
})
}
console.timeEnd('sessionCreate')
console.time('preProcess')
const [originalImg, originalMark] = await Promise.all([
imageFile instanceof HTMLImageElement
? imageFile
: loadImage(URL.createObjectURL(imageFile)),
loadImage(maskBase64),
])
const [img, mark] = await Promise.all([
processImage(originalImg),
processMark(
await resizeMark(originalMark, originalImg.width, originalImg.height)
),
])
const imageTensor = new ort.Tensor('uint8', img, [
1,
3,
originalImg.height,
originalImg.width,
])
const maskTensor = new ort.Tensor('uint8', mark, [
1,
1,
originalImg.height,
originalImg.width,
])
const Feed: {
[key: string]: any
} = {
[model.inputNames[0]]: imageTensor,
[model.inputNames[1]]: maskTensor,
}
console.timeEnd('preProcess')
console.time('run')
const results = await model.run(Feed)
console.timeEnd('run')
console.time('postProcess')
const outsTensor = results[model.outputNames[0]]
const chwToHwcData = postProcess(
outsTensor.data,
originalImg.width,
originalImg.height
)
const imageData = new ImageData(
new Uint8ClampedArray(chwToHwcData),
originalImg.width,
originalImg.height
)
console.log(imageData, 'imageData')
const result = imageDataToDataURL(imageData)
console.timeEnd('postProcess')
return result
}
|