Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
If you have ever wondered how to process your images using OpenCV with React Native, then youâre in the right place.
OpenCV together with React Native enables you to process images on mobile devices (most likely youâd like to process images taken by your deviceâs camera).
The top advantages of those are:
- Easy to implement.
- Easy to use.
- Lots of tutorials all over the Internet and solid official documentation of OpenCV.
- The size of your mobile app will be only a dozen or so megabytes bigger.
Let me show you how I used the OpenCV and React Native step by step to process my images, but first a few words of introduction.
What is OpenCV?
OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products.
The library has more than 2500 optimized algorithms, including a comprehensive set of both classic and state-of-the-art computer vision and machine learning algorithms.
These algorithms can be used to detect and recognize faces, identify objects, classify human actions in videos, track camera movements, track moving objects, extract 3D models of objects, produce 3D point clouds from stereo cameras, stitch images together to produce a high resolution image of an entire scene, find similar images from an image database, remove red eyes from images taken using flash, follow eye movements, recognize scenery and establish markers to overlay it with augmented reality, etc.
OpenCV has more than 47k people community and an estimated number of downloads exceeding 14Â million.
The library is used extensively in companies, research groups and by governmental bodies.
OpenCV is written natively in C++.
Since 2010 OpenCV was ported to the Android environment, it allows using the full power of the library in mobile applications development.
In 2012 OpenCV development team actively worked on adding extended support for iOS. Full integration is available since version 2.4.2Â (2012).
React Native was first released in 2015 by Facebook. React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components.
React Native and OpenCV are good friends!
If we google for âreact native opencvâ we stumble upon the following links:
- âGitHubâââma-pe/react-native-opencv: OpenCV Bindings for React âŠâAs the first words in the docs say: âCurrently being developed đ React Native Bindings for OpenCV. Yet there are no React Native bindings.â Also itâs incomplete and uploading 500+MB of the OpenCV library is not a good idea.
- âCan i use openCV in react native ?? · Issue #88 · wix/react-native âŠâAn unanswered question about React Native and OpenCV.
- âopencv/opencvâââGitHubâA problem with linking libraries with no indication on how to do it in the first place.
- â(Newbie) React Native with OpenCV : reactnativeâââRedditâAnswers are that itâs possible but with no example of how to do it.
What is this tutorial about?
In this tutorial, we will be building an example project which uses the deviceâs camera to take a photo, processes it with native code and returns the information if the taken image is blurred or clear.
Doing it in plain JavaScript would be highly ineffective. JavaScript is not sufficient for very heavy calculations.
Take a note that we are by no means Java or Objective-C developers hence our Java/Objective-C code may be far from good. If you want to contribute to this subject, please contact us.
OpenCV basic preparation
Step 1:react-native init reactNativeOpenCvTutorial
Step 2: Run downloadAndInsertOpenCV.sh script in your projectâs catalog (can be found here) which downloads and inserts openCV files for both Android and iOS. The paths in the file might not match your preferences so you may need to change them.
Tutorial for Android
Step 1: Open your project in Android Studio.
Step 2: Follow the tips in Android Studio for synchronizing your project.
Step 3: Download the newest version of OpenCV for Android. In my case, itâs 3.4.1.
Step 4: Import OpenCV to Android Studio: From File -> New -> Import Module, choose sdk/java folder in the unzipped OpenCVÂ archive.
Step 5: Update build.gradle under imported OpenCV module to update 4 fields to match your projectâs build.gradle:
- compileSdkVersion
- buildToolsVersion
- minSdkVersion
- targetSdkVersion.
Step 6: Add module dependency:
Application -> Module Settings, and select the Dependencies tab. Click + icon at the bottom, choose Module Dependency and select the imported OpenCVÂ module.
For Android Studio v1.2.2, to access Module Settings in the project view, right-click the dependent module and choose Open Module Settings.
Open up Module Settings.
Click on the +, select Module Dependency and select the OpenCV library from the list.
Step 7: Inside android/app/src/java create a package called i.e. com.reactlibrary.
Step 8: Update your Manifest with proper permissions:
<uses-permission android:name=âandroid.permission.CAMERAâ /><uses-permission android:name=âandroid.permission.READ_EXTERNAL_STORAGEâ /><uses-permission android:name=âandroid.permission.WRITE_EXTERNAL_STORAGEâ />
See the whole file.
Step 9: Create a file RNOpenCvLibraryModule.java inside your newly created package and fill it as shown here.
Step 10: Create a file called RNOpenCvLibraryPackage.java inside your newly created package and fill it as shown here.
Step 11: Add proper imports in your MainApplication.java file, add your OpenCV package to the list and proper code to the MainApplication class like this:
Imports:
import com.reactlibrary.RNOpenCvLibraryPackage;import org.opencv.android.BaseLoaderCallback;import org.opencv.android.LoaderCallbackInterface;import org.opencv.android.OpenCVLoader;import android.util.Log;
Add new RNOpenCvLibraryPackage() to your list of packages.
Add BaseLoaderCallback in your MainApplication class:
Also, add following callbacks to your MainApplication class:
See the whole file here.
Tutorial for iOS
Step 1: Open the iOS project in XCode.
Step 2: Add opencv2.framework to your Linked Frameworks and Libraries.
Step 3: Create a new group in the iOS catalog. I named it âOpenCVâ.
Step 4: Add a .pch file and insert it into the OpenCV catalog.
Step 5: Add proper content to your .pch fileâââshown here.
Step 6: Create a file named RNOpenCvLibrary.h and fill it as shown here.
Step 7: Create a file named RNOpenCvLibrary.mm and fill it as shown here.
Step 8: Set Precompile Prefix Header to Yes and set Prefix Header path like this:
Step 9: Add the following to your Info.plist file:
<key>NSCameraUsageDescription</key><string>Your message to user when the camera is accessed for the first time</string><key>NSPhotoLibraryAddUsageDescription</key><string>Your message to user when the photo library is accessed for the first time</string>
See the whole file.
Final partâââJavaScript
Step 1: Inside your src folder create a folder named e.g. NativeModules and a file named OpenCV.js, and fill it with:
import { NativeModules } from âreact-nativeâ;
export default NativeModules.RNOpenCvLibrary;
See the whole file.
Step 2: We will be using some third-party libraries for quick setup. Open up the terminal and type:
npm i âsave react-native-svgnpm i âsave react-native-cameranpm i âsave react-native-easy-toast
Step 3: Donât forget to link the libraries: react-native link.
We will be using this file as a reference.
In line 126 we set up the camera and in line 135 we create a touchable element to handle taking photos. Taking photos is handled by the takePicture function. It takes a photo, saves the data in the local state and proceeds to check if the photo is blurred. The function proceedWithCheckingBlurryImage uses native function checkForBlurryImage and returns a simple information if the photo is blurred or not.
Step 4: Note: if you encounter build problems for Android connected to the camera, refer to my build.gradle file, especially maven { url âhttps://jitpack.ioâ } line and resync the project in Android Studio.
If you have errors related to Google Play services, check this issue on GitHub.
If you have errors related to react-native-camera, check the master branch by changing the version in package.json like this:
âreact-native-cameraâ: âgit+https://git@github.com/react-native-community/react-native-camera"
Example results
An example clear photo. We receive a preview of the photo and have the option to either use it or repeat it.
An example blurred photo. We receive a toast message informing us that the photo is blurred and have to repeat it.
Donât forget to see the final product on our GitHub!
References:
- Setting up OpenCV for Android in Android Studio (StackOverflow)
- Setting up OpenCV for iOS in XCode (Blog post)
- Native modules for React Native (GitHub)
- Native Java code for checking if provided image is blurry (OpenCV official)
- Native Objective-C code for checking if provided image is blurry (StackOverflow)
- OpenCVâs official website (OpenCV official)
This was published on Brainhubâs blog here.
Looking for help to build your React Native or React application? Drop us a line.
How to Use OpenCV in React Native for Image Processing was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.