Cross-compiling OpenCV from x86_64-linux to aarch64-linux

At work I had a need for cross-compiling OpenCV from x86_64-linux to aarch64-linux for use on an edge device.

My coworker @considerate was able to get this successfully cross-compiling.

I wanted to share the overlay in case it helps anyone else attempting to cross-compile OpenCV:

final: prev: {
  opencv =
    (prev.opencv.override {
      # These are disabled to make cross-compiling easier.
      enableFfmpeg = false;
      enableGStreamer = false;
      enablePNG = false;
      enableJPEG = true;
      hdf5 = null;
    }).overrideAttrs (old: {
      nativeBuildInputs = old.nativeBuildInputs ++ [final.pkgsBuildHost.protobuf];
      cmakeFlags = old.cmakeFlags ++ [
        "-DWITH_OPENJPEG=OFF"
        "-DWITH_OPENEXR=OFF"
        "-DBUILD_opencv_photo=OFF"
        "-DBUILD_opencv_dnn=OFF"
      ];
    });
}

This is tested against the nixos-21.05 channel at commit nixos/ddccontrol: init · NixOS/nixpkgs@63ee5cd · GitHub. You can test this by building pkgsCross.aarch64-multiplatform.opencv on x86_64-linux.

If someone wanted to put some more work into it, it would probably be possible to fix and re-enable some of those additional dependencies (like ffmpeg, png, etc). It would also be nice to get this working by default in Nixpkgs (although I’m not sure how willing maintainers are to merge in things disabling a bunch of stuff just for a niche use-case).

4 Likes

In my tree I can build all deps besides hdf5, but opencv doesn’t work yet: https://github.com/Mindavi/nixpkgs/commit/b827fdf608002bd4db017ba8b7afc342887a1bb6. I’m slowly working to cleanup the patches and upstream them. Hopefully 21.11 will be in a better shape regarding cross-compilation support, but there’s still a lot to do.

2 Likes