I'm developing Android app on Android studio using Opencv library and when I try to open my app it opens then right after that it closes and displaying crash message. I'm new on mobile development
Using : OpenCV310, Android Studio 3.0,
public class ScanLicensePlateActivity extends AppCompatActivity {
protected AnylineOcrScanView scanView;
private LicensePlateResultView licensePlateResultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_anyline_ocr);
String license = getString(R.string.anyline_license_key);
// Get the view from the layout
scanView = (AnylineOcrScanView) findViewById(R.id.scan_view);
// Configure the view (cutout, the camera resolution, etc.) via json
// (can also be done in xml in the layout)
scanView.setConfig(new AnylineViewConfig(this, "license_plate_view_config.json"));
// Copies given traineddata-file to a place where the core can access it.
// This MUST be called for every traineddata file that is used
// (before startScanning() is called).
// The file must be located directly in the assets directory
// (or in tessdata/ but no other folders are allowed)
scanView.copyTrainedData("tessdata/GL-Nummernschild-Mtl7_uml.traineddata",
"8ea050e8f22ba7471df7e18c310430d8");
scanView.copyTrainedData("tessdata/Arial.traineddata", "9a5555eb6ac51c83cbb76d238028c485");
scanView.copyTrainedData("tessdata/Alte.traineddata", "f52e3822cdd5423758ba19ed75b0cc32");
scanView.copyTrainedData("tessdata/deu.traineddata", "2d5190b9b62e28fa6d17b728ca195776");
// Configure the OCR for license plate scanning via a custom script file
// This is how you could add custom scripts optimized by Anyline for your use-case
AnylineOcrConfig anylineOcrConfig = new AnylineOcrConfig();
anylineOcrConfig.setCustomCmdFile("license_plates.ale");
// set the ocr config
scanView.setAnylineOcrConfig(anylineOcrConfig);
// initialize with the license and a listener
scanView.initAnyline(license, new AnylineOcrListener() {
#Override
public void onReport(String identifier, Object value) {
// Called with interesting values, that arise during processing.
// Some possibly reported values:
//
// $brightness - the brightness of the center region of the cutout as a float value
// $confidence - the confidence, an Integer value between 0 and 100
// $thresholdedImage - the current image transformed into black and white
// $sharpness - the detected sharpness value (only reported if minSharpness > 0)
}
#Override
public boolean onTextOutlineDetected(List<PointF> list) {
// Called when the outline of a possible text is detected.
// If false is returned, the outline is drawn automatically.
return false;
}
#Override
public void onResult(AnylineOcrResult result) {
// Called when a valid result is found
String results[] = result.getText().split("-");
String licensePlate = results[1];
licensePlateResultView.setLicensePlate(licensePlate);
licensePlateResultView.setVisibility(View.VISIBLE);
}
#Override
public void onAbortRun(AnylineOcrError code, String message) {
// Is called when no result was found for the current image.
// E.g. if no text was found or the result is not valid.
}
});
// disable the reporting if set to off in preferences
if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
SettingsFragment.KEY_PREF_REPORTING_ON, true)) {
// The reporting of results - including the photo of a scanned meter -
// helps us in improving our product, and the customer experience.
// However, if you wish to turn off this reporting feature, you can do it like this:
scanView.setReportingEnabled(false);
}
addLicensePlateResultView();
}
private void addLicensePlateResultView() {
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
licensePlateResultView = new LicensePlateResultView(this);
licensePlateResultView.setVisibility(View.INVISIBLE);
mainLayout.addView(licensePlateResultView, params);
licensePlateResultView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startScanning();
}
});
}
private void startScanning() {
licensePlateResultView.setVisibility(View.INVISIBLE);
// this must be called in onResume, or after a result to start the scanning again
scanView.startScanning();
}
#Override
protected void onResume() {
super.onResume();
startScanning();
}
#Override
protected void onPause() {
super.onPause();
scanView.cancelScanning();
scanView.releaseCameraInBackground();
}
#Override
public void onBackPressed() {
if (licensePlateResultView.getVisibility() == View.VISIBLE) {
startScanning();
} else {
super.onBackPressed();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}}
source code is here.
If possible please help.
Logcat error shown here
Ideally more information regarding the error would be best i.e the opencv library version etc. Given it seems to be an Android issue, I would advise
File and issue or view issues pertaining to this error on their github page. Search for related Android errors to see if they match.
IF you cannot find a related error, file an issue there.
Related
I have a project that use Android to display Unity Player. So I export Untiy project as Android module which implemented by Android Application.
I create buttons in Android Activity which contains UnityPlayer, And when I click button, it send a message to Unity Player to invoke C# function, just like this:
findViewById(R.id.btnChange).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mUnityPlayer.UnitySendMessage("ScriptHolder", "ChangeSkin", "");
}
});
And the function named "ChangeSkin" is just to change some GameObjects' active. Just like this:
void ChangeSkin()
{
int prefab;
if (_currentPrefab == PREFAB_DEFAULT)
{
prefab = PREFAB_PRINCESS;
}
else
{
prefab = PREFAB_DEFAULT;
}
ShowSkin(prefab);
}
private void ShowSkin(int prefab)
{
_currentPrefab = prefab;
foreach (var item in _defaultDressList)
{
item.SetActive(prefab == PREFAB_DEFAULT);
}
foreach (var item in _princessDressList)
{
item.SetActive(prefab == PREFAB_PRINCESS);
}
}
And something weird happening: when I click button to change the person's cloth in Unity, the GameObjects which called SetActive(true) show at the position above the right position for a frame and become normal, it looks like they flash. Here is the gif of the project demo:
It looks like the position offset is equal to the height of status bar. If I create a button on Unity Scene and call "ChangeSkin" function, everything will be OK.
I tried all I can to fix this but not succeed. So I hope you will help me, thx.
You should check your Unity layout. If you have a layout group that has content size fitter component, and the child objects also have it (content size fitter), this could cause these glitches.
I fixed this problem by using a flag (or trigger). Just like this:
// set value true to trigger ChangeSkin() in Update(),
// instead of invoke ChangeSkin() directly
private bool _changingSkinTrigger = false;
void ChangeSkin()
{
if (_currentPrefab == PREFAB_DEFAULT)
{
_currentPrefab = PREFAB_PRINCESS;
}
else
{
_currentPrefab = PREFAB_DEFAULT;
}
_changingSkinTrigger = true;
}
void Update()
{
if (_changingSkinTrigger)
{
_changingSkinTrigger = false;
ShowSkin();
}
}
private void ShowSkin()
{
foreach (var item in _defaultDressList)
{
item.SetActive(_currentPrefab == PREFAB_DEFAULT);
}
foreach (var item in _princessDressList)
{
item.SetActive(_currentPrefab == PREFAB_PRINCESS);
}
}
Thank #AndriyMarshalek for enlightening me.
Unable to override Here SDK to disable sound effect on the onSpeedExceeded event.
Using the Here Developer tutorial, (https://developer.here.com/blog/android-premium-sdk-speed-limit-warning-example), I succeeded in running the sample app. But...
While driving, when I exceed the speed limit, there is a doot doot doot. I want to override this behaviour as I intend to use my own sounds.
I guessed that I might override the code by creating a NavigationManager.SpeedWarningListener. Unfortunately I can not disable or defeat the 'onSpeedExceeded' sound effects.
NavigationManager.SpeedWarningListener speedWarningListener = new NavigationManager.SpeedWarningListener() {
#Override
public void onSpeedExceeded(String s, float v) {
//super.onSpeedExceeded(s, v);
//Log.v(Global.TAG, "onSpeedExceeded");
Global.SpeedLimitExceeded = true;
}
#Override
public void onSpeedExceededEnd(String s, float v) {
//super.onSpeedExceededEnd(s, v);
//Log.v(Global.TAG, "onSpeedExceededEnd");
Global.SpeedLimitExceeded = false;
}
};
EDITED ANSWER: This method needs to be amended to stop the speed warning:
private void startNavigationManager() {
NavigationManager.Error navError = NavigationManager.getInstance().startTracking();
// added by suggestion from stackoverflow
NavigationManager.getInstance().stopSpeedWarning();
if (navError != NavigationManager.Error.NONE) {
Log.d(Global.TAG, "NavigationManager: false");
//handle error navError.toString());
} else {
//Log.d(Global.TAG, "NavigationManager: true");
}
}
Please set speedWarningEnabled accordingly for NMANavigationManager
navigationManager:didUpdateSpeedingStatus:forCurrentSpeed:speedLimit: will be sent to the delegate when speeding is detected or when a correction is made.
Also refer http://developer.here.com/documentation/ios-premium/api_reference_jazzy/Classes/NMANavigationManager.html
i have a sales summary print out and has a QR Code ,
i want to develop an app (IOS and android) that reads the QR code , extract all information,do some calculations,and display in specific form , i tried zxing library but it did not extract all information from the receipt.any tip?
You can use google vision API to achieve this. I personally used this and found it great. The below code snippets should help you.
Put this below line in the gradle.
compile 'com.google.android.gms:play-services:9.4.0'
Use BarcodeDetector and CameraSource classes to capture the QR code on real time and decode it.
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeInfo.post(new Runnable() { // Use the post method of the TextView
public void run() {
barcodeInfo.setText( // Update the TextView
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
Use a SparseArray to fetch the detections and the displayValue of the elements of this sparse array returns the deocded string.
After extracting the string one can do anything, be it displaying the string or make some calculation out of it etc.
This library is the most popular and easiest of reading QR codes in your Android application.
You should also have a look at the Wiki section of this library for learning about how to integrate this library into your Android Application and how to use this library.
This is how you can use this library.
1. Add this library to your project by adding following line into your dependencies inside build.gradle(Module: app) file
compile 'com.github.nisrulz:qreader:2.0.0'
2. Then, after syncing project files, add the SurfaceView element provided by this library into your XML layout file.
<SurfaceView
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
3. Declare the SurfaceView & QREader inside your Activity's Java file & then initialize it inside onCreate() method.
class MainActivity extends AppCompatActivity{
private SurfaceView mySurfaceView;
private QREader qrEader;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup SurfaceView
// -----------------
mySurfaceView = (SurfaceView) findViewById(R.id.camera_view);
// Init QREader
// ------------
qrEader = new QREader.Builder(this, mySurfaceView, new QRDataListener() {
#Override
public void onDetected(final String data) {
Log.d("QREader", "Value : " + data);
text.post(new Runnable() {
#Override
public void run() {
text.setText(data);
}
});
}
}).facing(QREader.BACK_CAM)
.enableAutofocus(true)
.height(mySurfaceView.getHeight())
.width(mySurfaceView.getWidth())
.build();
}
4. Initialize it inside onResume()
#Override
protected void onResume() {
super.onResume();
// Init and Start with SurfaceView
// -------------------------------
qrEader.initAndStart(mySurfaceView);
}
There are many more possibilities you can do with this library, so I recommend you to visit the GitHub repository and check it out. It's worth a shot!
I am trying to integrate anyline ocr sdk to extract url links from an image.
From their documentation I understood that by modifying the iban scanner example i can achieve the same results for an url.
Here is the config file for scan view
{
"captureResolution":"1080",
"cutout": {
"style": "rect",
"maxWidthPercent": "80%",
"maxHeightPercent": "80%",
"alignment": "top_half",
"width": 900,
"ratioFromSize": {
"width": 10,
"height": 1
},
"strokeWidth": 2,
"cornerRadius": 10,
"strokeColor": "FFFFFF",
"outerColor": "000000",
"outerAlpha": 0.3,
"feedbackStrokeColor": "0099FF"
},
"flash": {
"mode": "manual",
"alignment": "bottom_right"
},
"beepOnResult": true,
"vibrateOnResult": true,
"blinkAnimationOnResult": true,
"cancelOnResult": true,
"visualFeedback": {
"style": "contour_point",
"strokeColor": "0099FF",
"strokeWidth": 2,
"fillColor": "110099FF"
}
}
Code for ScanURLActivity.java
public class ScanURLActivity extends AppCompatActivity {
private static final String TAG = ScanURLActivity.class.getSimpleName();
private AnylineOcrScanView scanView;
private URLResultView urlResultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_anyline_ocr);
addURLResultView();
String license = getString(R.string.anyline_license_key);
// Copies given traineddata-file to a place where the core can access it.
// This MUST be called for every traineddata file that is used (before startScanning() is called).
// The file must be located directly in the assets directory (or in tessdata/ but no other folders are allowed)
scanView = new AnylineOcrScanView(getApplicationContext(),null);
scanView.copyTrainedData("tessdata/eng_no_dict.traineddata", "d142032d86da1be4dbe22dce2eec18d7");
scanView.copyTrainedData("tessdata/deu.traineddata", "2d5190b9b62e28fa6d17b728ca195776");
//Configure the OCR for URLs
AnylineOcrConfig anylineOcrConfig = new AnylineOcrConfig();
// use the line mode (line length and font may vary)
anylineOcrConfig.setScanMode(AnylineOcrConfig.ScanMode.LINE);
// set the languages used for OCR
anylineOcrConfig.setTesseractLanguages("eng_no_dict", "deu");
// allow only capital letters and numbers
anylineOcrConfig.setCharWhitelist("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz.\\:");
// set the height range the text can have
anylineOcrConfig.setMinCharHeight(20);
anylineOcrConfig.setMaxCharHeight(60);
// The minimum confidence required to return a result, a value between 0 and 100.
// (higher confidence means less likely to get a wrong result, but may be slower to get a result)
anylineOcrConfig.setMinConfidence(65);
// a simple regex for a basic validation of the URL, results that don't match this, will not be returned
// (full validation is more complex, as different countries have different formats)
anylineOcrConfig.setValidationRegex("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]#!\\$&'\\(\\)\\*\\+,;=.]+$");
// removes small contours (helpful in this case as no letters with small artifacts are allowed, like iöäü)
anylineOcrConfig.setRemoveSmallContours(true);
// removes whitespaces from the result
// (also causes faster processing, because optimizations can be made if whitespaces are not relevant)
anylineOcrConfig.setRemoveWhitespaces(true);
// Experimental parameter to set the minimum sharpness (value between 0-100; 0 to turn sharpness detection off)
// The goal of the minimum sharpness is to avoid a time consuming ocr step,
// if the image is blurry and good results are therefor not likely.
anylineOcrConfig.setMinSharpness(66);
// set the ocr config
scanView.setAnylineOcrConfig(anylineOcrConfig);
// set an individual focus configuration for this example
FocusConfig focusConfig = new FocusConfig.Builder()
.setDefaultMode(Camera.Parameters.FOCUS_MODE_AUTO) // set default focus mode to be auto focus
.setAutoFocusInterval(8000) // set an interval of 8 seconds for auto focus
.setEnableFocusOnTouch(true) // enable focus on touch functionality
.setEnablePhaseAutoFocus(true) // enable phase focus for faster focusing on new devices
.setEnableFocusAreas(true) // enable focus areas to coincide with the cutout
.build();
// set the focus config
scanView.setFocusConfig(focusConfig);
// set the highest possible preview fps range
scanView.setUseMaxFpsRange(true);
// set sports scene mode to try and bump up the fps count even more
scanView.setSceneMode(Camera.Parameters.SCENE_MODE_SPORTS);
// initialize with the license and a listener
scanView.initAnyline(license, new AnylineOcrListener() {
#Override
public void onReport(String identifier, Object value) {
// Called with interesting values, that arise during processing.
// Some possibly reported values:
//
// $brightness - the brightness of the center region of the cutout as a float value
// $confidence - the confidence, an Integer value between 0 and 100
// $thresholdedImage - the current image transformed into black and white
// $sharpness - the detected sharpness value (only reported if minSharpness > 0)
}
#Override
public boolean onTextOutlineDetected(List<PointF> list) {
// Called when the outline of a possible text is detected.
// If false is returned, the outline is drawn automatically.
return false;
}
#Override
public void onResult(AnylineOcrResult result) {
// Called when a valid result is found (minimum confidence is exceeded and validation with regex was ok)
urlResultView.setResult(result.getText());
urlResultView.setVisibility(View.VISIBLE);
}
#Override
public void onAbortRun(AnylineOcrError code, String message) {
// Is called when no result was found for the current image.
// E.g. if no text was found or the result is not valid.
}
});
// disable the reporting if set to off in preferences
if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
SettingsFragment.KEY_PREF_REPORTING_ON, true)) {
// The reporting of results - including the photo of a scanned meter -
// helps us in improving our product, and the customer experience.
// However, if you wish to turn off this reporting feature, you can do it like this:
scanView.setReportingEnabled(false);
}
urlResultView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlResultView.setVisibility(View.INVISIBLE);
scanView.startScanning();
}
});
}
private void addURLResultView() {
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
urlResultView = new URLResultView(this);
urlResultView.setVisibility(View.INVISIBLE);
mainLayout.addView(urlResultView, params);
}
#Override
protected void onResume() {
super.onResume();
scanView.startScanning();
}
#Override
protected void onPause() {
super.onPause();
scanView.cancelScanning();
scanView.releaseCameraInBackground();
}
#Override
public void onBackPressed() {
if (urlResultView.getVisibility() == View.VISIBLE) {
urlResultView.setVisibility(View.INVISIBLE);
scanView.startScanning();
} else {
super.onBackPressed();
}
}
}
The AnylineOCRlistener is unable to detect any ocr results despite confidence set at 65.
Code for URLResultView.java class
public class URLResultView extends RelativeLayout {
private TextView resultText;
public URLResultView(Context context) {
super(context);
init();
}
public URLResultView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public URLResultView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setPadding(DimensUtil.getPixFromDp(getContext(), 4), DimensUtil.getPixFromDp(getContext(), 16),
DimensUtil.getPixFromDp(getContext(), 4), DimensUtil.getPixFromDp(getContext(), 16));
//setBackgroundResource(R.drawable.);
inflate(getContext(), R.layout.url_result, this);
resultText = (TextView) findViewById(R.id.text_result);
}
public void setResult(String result) {
resultText.setText(result.trim());
}
}
Can someone help me with this integration as i am unable to find any other resource/tutorial other than their documentation and sdk samples.
Actually there are two problems that you ran into:
You only added the backslash \ to the charWhitelist, not the slash /
You have to set removeSmallContours to false
removeSmallContours removes everything from the line that is smaller than the minCharHeight. So in your case, it will remove the : and ., because they are too small for the SDK.
After changing these two settings, the scanning works fine with a minConfidence of 85.
I'm trying to implement PlayHaven's SDK in my Android application and while I do get Interstital ads, I cannot seem to capture the event of content dismissed.
I do get a log when the content is loaded.
This is what I've tried:
PlayHaven.configure(this, R.string.token, R.string.secret);
OpenRequest open = new OpenRequest();
open.send(this);
placement = new Placement("some_placement");
placement.setListener(pl); //PlacementListener
placement.preload(this);
The PlacementListener(pl) implementation:
private PlacementListener pl = new PlacementListener() {
#Override
public void contentLoaded(Placement placement) {
Log.i(TAG_PH, "PlayHaven contentLoaded");//this log is displayed
startActivity(FullScreen.createIntent(Splash.this,placement));
}
#Override
public void contentFailed(Placement placement, PlayHavenException e) {
Log.i(TAG_PH, "PlayHaven contentFailed");
}
#Override
public void contentDismissed(Placement placement, DismissType dismissType,
Bundle data) {
Log.i(TAG_PH, "PlayHaven content Dismissed");//this log is **NOT** displayed
}
};
In your onActivityResult method, you can use the following code:
String placementTag = data.getStringExtra(PlayHavenView.BUNDLE_PLACEMENT_TAG);
PlayHavenView.DismissType dismissType = (PlayHavenView.DismissType) data.getSerializableExtra(PlayHavenView.BUNDLE_DISMISS_TYPE);
You will get back dismissType. The values you are looking for are EmergencyClose (triggered when a user clicks on the X button to close a content unit), NoThanks (user declines the content unit offer), SelfClose (the Content Unit dismisses itself which happens when the SDK has to intelligently close a content unit), and BackButton (when the user presses back).