How to detect and highlight the edges of an image in Java
2 min readJan 28, 2020
Edge detection can be a difficult feature to implement into a photo app. Today, we will be looking at how to accomplish this without all the headache. In fact, we should be finished in just a few minutes. Let’s get started
First we need to dynamically compile our library using Jitpack. This will require the following references to be added to pom.xml:
Repository
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependency
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>
Now call filterEdgeDetect, provide an image and effect radius:
// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.FilterApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");FilterApi apiInstance = new FilterApi();Integer radius = 56; // Integer | Radius in pixels of the edge detection operation; a larger radius will produce a greater effectFile imageFile = new File("/path/to/file"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try {byte[] result = apiInstance.filterEdgeDetect(radius, imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FilterApi#filterEdgeDetect");e.printStackTrace();}
And we are done! It’s really that simple. Let’s use this photo to test it out:
We shall set the radius to 1 and here is what we get: