🏠 back to Observable

OpenCV.JS on Observablehq

Hi,
I tried to run a small script using OpenCV.JS work on Observablehq. The details of the script are mentioned in the below link: OpenCV: Image Thresholding

I am facing a problem in importing openCV on Observablehq. Please find my Observablehq notebook here OpenCV JS testing / Joy S / Observable

Any help will be highly appreciable.

It looks like you are trying to use raw javascript in a notebook cell.
The JS code needs to be wrapped in {}'s

You might be better using something like p5.js Web Editor or opencv-js-face-detection - CodeSandbox

I haven’t seen any successful attempt at loading opencv in Observable. The most important blocker is that you need to compile it to wasm, then load the wasm file through observable. There is an example with a pre-compiled wasm in codepen https://codepen.io/huningxin/pen/gxRKdo ; but I’m at a loss when it comes to porting it to obs.

Thank you so much for your valuable suggestions. Does it mean that there is no direct way to use OpenCv.JS in Observablehq?

The problem is two-fold:

  1. d3-require registers window.define, which causes the opencv package to register itself via define instead of in addition to registering a global cv object.
  2. The cv object is a thenable, meaning it has a then function that again returns the object. When one attempts to load opencv via d3-require (i.e., Observable’s require()), the promise resolution gets stuck in an infinite loop.

I fear there’s no good solution here. Presumably one would have to replace and wrap require's define(), so that it can still work for other libraries, but won’t end up in an infinite cycle when returning cv.

1 Like

Alright, here we go:

5 Likes

Very cool hack @mootari! note this package is big!

I’m aware, but I don’t know of any other (semi-)official sources. The source is already minified, and afaik you’d have to hand-pick and create your own build if you want to push the size down further.

The unofficial opencv.js package hasn’t been updated in over four years (stuck at 1.2.1), which is likely the only reason for its smaller size.

1 Like

@mootari It solved my problem. Thanks a lot!

1 Like

Super cool, @mootari! Might I suggest replacing the Lena image with something else since its usage can be considered sexist and the model herself has said it’s time to ditch it as a sample image? (Here’s a nifty interactive about it.)

3 Likes

Losing Lena, the documentary, is very good: https://www.losinglena.com/

1 Like

Good point, thanks! I had used the image despite knowing its history to stick closer to the original example, a rather weak argument in hindsight. I’ve now replaced the image.

2 Likes