How do I integrate QR code reading application to Sony SmartEyeGlass? - android-studio

We are developing an application for Sony SmartEyeGlass. Firstly, we created it with Android Studio and android tablet.Now, we are working with Sample Camera Extension sample to integrate it our Project. But there is a lot of details. Someone can help about this subject?

The Sample Camera extension is a great place to start building your QR code reader. In the SampleCameraControl.java there is a function called cameraEventOperation. In this function you will see an example of how to pull the camera data down in to a bitmap. Here is the code for reference:
private void cameraEventOperation(CameraEvent event) {
if ((event.getData() != null) && ((event.getData().length) > 0)) {
data = event.getData();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
You can take this data and send it to your QR code reader to scan for QR codes. Let me know if this helps!
----- Update ----
You can use a function like this to pass a bitmap to the Google Zxing library. Use should put this in something like an Async task:
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
//This function sends the provided bitmap to Google Zxing
public static String readBarcodeImage(Bitmap bMap) {
String contents = null;
int[] intArray = new int[bMap.getWidth()*bMap.getHeight()];
//copy pixel data from the Bitmap into the 'intArray' array
bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(), intArray);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();// use this otherwise ChecksumException
try {
Hashtable<DecodeHintType,Object> hints=new Hashtable<DecodeHintType,Object>();
hints.put(DecodeHintType.TRY_HARDER,Boolean.TRUE);
Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
decodeFormats.add(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS,decodeFormats);
Result result = reader.decode(bitmap, hints);
BarcodeFormat format = result.getBarcodeFormat();
contents = result.getText() + " : "+format.toString();
} catch (NotFoundException e) { e.printStackTrace(); }
catch (ChecksumException e) { e.printStackTrace(); }
catch (FormatException e) { e.printStackTrace(); }
return contents;
}

Related

Transcode SVG to JPEG

my picture in SVG format include the latest data 122.6 but in JPEG format the last data point is 122.1
How can I convert the image in svg-format to jpeg-format without the lost of the latest data
renderer ?
padding margins ?
size ?
What is wrong in my code ??
best ghost
package helix;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.fop.svg.PDFTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.ext.awt.image.codec.*;
public class genesisMATPIsvg2jpg {
public static void main(String[] args) throws Exception {
//Step -1: We read the input SVG document into Transcoder Input
String svg_URI_input = new File(basePath + "/var/gWebClient/Materialkostenindex2015=100.svg").toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to JPG file and attach to TranscoderOutput
OutputStream jpg_ostream = new FileOutputStream(basePath + "/var/gWebClient/Materialkostenindex2015=100.jpeg");
TranscoderOutput output_jpg_image = new TranscoderOutput(jpg_ostream);
// Step-3: Create JPEGTranscoder and define hints
JPEGTranscoder my_converter = new JPEGTranscoder();
Object jpegQuality1 = new Float(800);
Object jpegQuality2 = new Float(600);
my_converter.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, jpegQuality1);
my_converter.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, jpegQuality2);
my_converter.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(0.9));
// Step-4: Write output
my_converter.transcode(input_svg_image, output_jpg_image);
// Step 5- close / flush Output Stream
jpg_ostream.flush();
jpg_ostream.close();
}
}

What changes are required to make this class scan Barcode in any direction. It works only for QR codes

I am developing a Qr Code and Barcode Scanner App, using CameraX and Zxing but the following class only works for Qr Code. I want to scan barcodes as well from any orientation on an android device
Code Scanning class:
public class QRCodeImageAnalyzer implements ImageAnalysis.Analyzer {
private QRCodeFoundListener listener;
public QRCodeImageAnalyzer(QRCodeFoundListener listener) {
this.listener = listener;
}
#SuppressLint("UnsafeOptInUsageError")
#Override
public void analyze(#NonNull ImageProxy imageProxy) {
Image image = imageProxy.getImage();
if (image.getFormat() == YUV_420_888 || image.getFormat() == YUV_422_888 || image.getFormat() == YUV_444_888) {
ByteBuffer byteBuffer = image.getPlanes()[0].getBuffer();
byte[] imageData = new byte[byteBuffer.capacity()];
byteBuffer.get(imageData);
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
imageData,
image.getWidth(), image.getHeight(),
0, 0,
image.getWidth(), image.getHeight(),
false
);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = new QRCodeMultiReader().decode(binaryBitmap);
listener.onQRCodeFound(result.getText());
} catch (FormatException | ChecksumException | NotFoundException e) {
listener.qrCodeNotFound();
}
}
imageProxy.close();
}
}
I also tried this class CameraX with MLKit: I tried the sample from the official docs of MLKit provided in the first answer but it scan nothing neither QR Code nor Barcode. Please take a look if I put things the wrong way.
import android.annotation.SuppressLint
import android.util.Log
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.Barcode
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage
#UseExperimental(markerClass = [ExperimentalGetImage::class])
class QrCodeAnalyzer(
private val onQrCodesDetected: (qrCodes: List<Barcode>?) -> Unit
) : ImageAnalysis.Analyzer {
private val TAG: String = "Kamran"
private fun rotationDegreesToFirebaseRotation(rotationDegrees: Int): Int {
return when (rotationDegrees) {
0 -> 0
90 -> 1
180 -> 2
270 -> 3
else -> throw IllegalArgumentException("Not supported")
}
}
#SuppressLint("UnsafeOptInUsageError")
override fun analyze(image: ImageProxy) {
val rotation = rotationDegreesToFirebaseRotation(image.imageInfo.rotationDegrees)
image.image?.let{
val optionss = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_EAN_8,
Barcode.FORMAT_EAN_13)
.build()
val imageValue = InputImage.fromMediaImage(it, image.imageInfo.rotationDegrees)
//val options = BarcodeScannerOptions.Builder().setBarcodeFormats(Barcode.FORMAT_QR_CODE).build()
val scanner = BarcodeScanning.getClient(optionss)
scanner.process(imageValue)
.addOnCompleteListener { barcodes ->
barcodes.result?.forEach { barcode ->
val bounds = barcode.boundingBox
val corners = barcode.cornerPoints
val rawValue = barcode.rawValue
}
onQrCodesDetected(barcodes.result)
image.image?.close()
image.close()
Log.d(TAG, "Successfully got inside onCompleteListener")
}
.addOnFailureListener { failure ->
failure.printStackTrace()
image.image?.close()
image.close()
}
}
}
}
I am not sure If using ZXing android library is a requirement (afaik it is no longer developed). If it is not a hard requirement, I would suggest you to give it a try for MLKit Barcode Scanner. It scans QR as well.
Also, you would probably find it easier to implement with CameraX as they already have multiple examples and sample code.
For example check this guide for step by step instructions.
Particularly this part.
You can configire the scanner first:
val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_EAN_8,
Barcode.FORMAT_EAN_13)
.build()
then;
private class YourImageAnalyzer : ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image
if (mediaImage != null) {
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
// Pass image to an ML Kit Vision API
// ...
}
}
}
finally this is how you get it decoded:
val result = scanner.process(image)
.addOnSuccessListener { barcodes ->
// Task completed successfully
// ...
}
.addOnFailureListener {
// Task failed with an exception
// ...
}

Image downloaded from Azure Storage not being displayed

I'm new to Xamarin. I'm trying display a list of downloaded images. I am downloading images from an APP API on Azure, where I stored the file on Azure Storage.
My server code is the following:
public HttpResponseMessage Get(string PK, string RK)
{
//Creating CloudBlockBlolb...
byte[] bytes = new byte[blockBlob.Properties.Length]
for(int i = 0; i < blockBlob.Properties.Length; i++){
bytes[i] = 0x20;
}
blockBlob.DownloadToByteArray(bytes, 0);
HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new ByteArrayContent(bytes);
resp.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpg");
return resp;
}
My Xamarin code is the following:
public MainPage ()
{
//...
List<PicturePost> list = new List<PicturePost>{
new PicturePost("title", "subtitle", "link/api/Pictures?PK=xxx&RK=yyy")
};
InitializeComponent ();
listView.ItemTemplate = new DataTemplate (typeof(CustomImageCell));
listView.HasUnevenRows = true;
listView.ItemsSource = list;
//...
}
And here is the relevant code for CustomImageCell:
var image = new Image ();
image.SetBinding (Image.SourceProperty, "image");
//...
horizontalLayout.Children.Add (image);
I know that my API call works, because when I test it on the browser, it returns the image. I also know that if I use any random links such as http://www.natureasia.com/common/img/splash/thailand.jpg the image is downloaded and displayed properly. It is only when I use the API link that it doesn't seem to be working. Can someone tell me what I am doing wrong?
so in my public MainPage(), I added the following:
listView.BeginRefresh ();
listView.EndRefresh ();
I realized at some point that the images would take some time to download. I assume that when the listView was created, the images were not finished downloading, so I added the code above... Pretty sure this is not the best way to do this (probably an await would be better, but I don't know where).

Converting UIImage to UIData in monotouch fails

I've seen variations of my questions on stack overflow but haven't had any answers that have worked for me. I'm trying to convert an image I retrieve via UIImagePickerController to an NSData object. In the debugger after I call AsJPEG the NSData object has text that appears as...
System.Exception: Could not initialize an instance of the type 'MonoTouch.Foundation.NSString': the native 'initWithDa…
(note the debugger cuts off the string)
My code is fairly straight forward (taken form samples on stack overflow)
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e) {
// determine what was selected, video or image
bool isImage = false;
switch(e.Info[UIImagePickerController.MediaType].ToString()) {
case "public.image":
Console.WriteLine("Image selected");
isImage = true;
break;
case "public.video":
Console.WriteLine("Video selected");
break;
}
string path = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
path = Path.Combine (path, "media");
if (!Directory.Exists (path))
Directory.CreateDirectory (path);
path = Path.Combine (path, Path.GetRandomFileName ());
// get common info (shared between images and video)
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
if (referenceURL != null)
Console.WriteLine("Url:"+referenceURL.ToString ());
// if it was an image, get the other image info
if(isImage) {
// get the original image
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if(originalImage != null) {
// do something with the image
Console.WriteLine ("got the original image");
using (NSData imageData = originalImage.AsJPEG(0.75f)) {
byte[] dataBytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, dataBytes, 0, Convert.ToInt32(imageData.Length));
File.WriteAllBytes (path, dataBytes);
}
}
} else { // if it's a video
// get video url
NSUrl mediaURL = e.Info[UIImagePickerController.MediaURL] as NSUrl;
if(mediaURL != null) {
// ...
}
}
// dismiss the picker
NavigationController.DismissViewController (true, null);
}
I've seen other posts that suggested it was the size of the UIImage, so I've experimented with cropping it. Same result. I've also tried AsPNG, same result. I even tried scaling down the image to 1/4 it's original size and still get the error.
I think the key is the mention of NSString, which tells me something's fishy... as the native C call used in Xcode doesn't involve an NSString, so I think something else is going on.
Any suggestions?
As noted in the comment from therealjohn, this appears to be an error with the debugger when it converts a value to a string to display it in the debugger window it seems to run into an error. The NSData object is actually fine.

Null pointer exception config file

I am trying to familiarize myself with Sphinx by dissecting the config file.
Unfortunately, I haven't been able to get it to compile. I did this by using the same class contents of the helloworld example, removed the config file listed and replaced it with the one shown in http://cmusphinx.sourceforge.net/sphinx4/javadoc/edu/cmu/sphinx/util/props/doc-files/ConfigurationManagement.html
I am getting a null pointer exception and can't figure out why. I imported sphinx4.jar, WSJ_8gau....jar, js.jar, and jsapi.jar. I know it is reading from the config file. It was compiling correctly when I left it as
HelloWorld.class.getResource("helloworld.config.xml").
Below is the code with the slight changes made.
package speechcapture;
//import edu.cmu.sphinx.demo.helloworld.HelloWorld;
import edu.cmu.sphinx.frontend.util.Microphone;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;
public class capturespeech {
public void speechtolist(String[] args){
ConfigurationManager cm;
if (args.length > 0) {
cm = new ConfigurationManager(args[0]);
} else {
cm = new ConfigurationManager("testing.config.xml");
}
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
recognizer.allocate(); //Where error occurs
// start the microphone or exit if the program if this is not possible
Microphone microphone = (Microphone) cm.lookup("microphone");
if (!microphone.startRecording()) {
System.out.println("Cannot start microphone.");
recognizer.deallocate();
System.exit(1);
}
System.out.println("Say: (Good morning | Hello) ( Bhiksha | Evandro | Paul | Philip | Rita | Will )");
// loop the recognition until the program exits.
while (true) {
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
Result result = recognizer.recognize();
if (result != null) {
String resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + '\n');
} else {
System.out.println("I can't hear what you said.\n");
}
}
}
}
Recognizer was null on this line:
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
recognizer.allocate(); //Where error occurs
because component named "recognizer" was missing in the config xml file. When you update XML file check that code is in sync.
For more details see the original discussion:
https://sourceforge.net/p/cmusphinx/discussion/sphinx4/thread/91efe5b7/?limit=25#52da

Resources