Java with OpenCV failed to read PNG image - java

SOLVED & WHY:
Path to image contains Unicode character, I have to say it's a bug.
ORIGINAL POST:
I am new to OpenCV and just use java with OpenCV 3.2.0, 3.1.0, and 2.4.3 to read this image without any success, namely, no width or height can be read, though my aim is to find the harris corners, and use other image is without this problem.
code:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
public class Test
{
public static void main (String []args)
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat img_object = Highgui.imread("E:/ℤIMAGEℂ/ℤtestℂ.png");
System.out.println(
"img_object.width() = " + img_object.width()
+ ",\n img_object.height() = " + img_object.height()
+ ",\n img_object.depth() = " + img_object.depth()
+ ",\n img_object.channels() = " + img_object.channels()
+ ",\n img_object.total() = " + img_object.total()
+ ",\n img_object.type() = " + img_object.type()
);
}
}
Image:
error:
img_object.width() = 0,
img_object.height() = 0,
img_object.depth() = 0,
img_object.channels() = 1,
img_object.total() = 0,
img_object.type() = 0
libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data
OpenCV Error: Assertion failed (code) in cv::imencode, file ..\..\..\..\opencv\modules\highgui\src\loadsave.cpp, line 430
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\highgui\src\loadsave.cpp:430: error: (-215) code in function cv::imencode
]
at org.opencv.highgui.Highgui.imencode_1(Native Method)
at org.opencv.highgui.Highgui.imencode(Highgui.java:243)
at Imshow.imshow(Imshow.java:29)
at test.main(Test.java:21)

SOLVED & WHY:
Path to image contains Unicode character.
As someone suggests if you solve your problem, delete it or answer it.
If you try to read image from Unicode path, errors occur, and I didn't see related solution, so you can read this.
OpenCV is bugged with Unicode file path, sadly. That's the problem of OpenCV but mine.

Related

Dovx4J: Enabling page numbers in ToC results in TocException

I am using Docx4j in an internship project and when I try to generate a ToC with page numbers it does not work.
Executing the code with
if (template.isGenerateToc()) {
Toc.setTocHeadingText("Inhaltsverzeichnis");
TocGenerator tocGenerator = new TocGenerator(wordPackage);
tocGenerator.generateToc(2, " TOC \\o \"1-3\" \\h \\z \\u ", true);
}
Works perfectly fine, but results in no page numbers in the .docx (when exporting to PDF via the Gotenberg API (https://gotenberg.dev), the page numbers are existant and correct).
When I try to pass "false" for the third parameter, the application crashes with the following exception/stacktrace:
org.docx4j.toc.TocException: Exception exporting package
at org.docx4j.toc.TocGenerator.getPageNumbersMapViaFOP(TocGenerator.java:871)
at org.docx4j.toc.TocGenerator.getPageNumbersMap(TocGenerator.java:694)
at org.docx4j.toc.TocGenerator.populateToc(TocGenerator.java:441)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:306)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:234)
at org.docx4j.toc.TocGenerator.generateToc(TocGenerator.java:194)
If usefull: This is my TocHeading:
private static String XML_TOCHeading_BasedOn_Nothing = "<w:style w:styleId=\"TOCHeading\" w:type=\"paragraph\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
+ "<w:name w:val=\"TOC Heading\"/>"
// + "<w:basedOn w:val=\"Heading1\"/>" // would be ok if provided already present, since
+ "<w:next w:val=\"Normal\"/>"
+ "<w:uiPriority w:val=\"39\"/>"
+ "<w:semiHidden/>"
+ "<w:unhideWhenUsed/>"
+ "<w:qFormat/>"
+ "<w:pPr>"
+ "<w:keepNext/>"
+ "<w:keepLines/>"
+ "<w:spacing w:after=\"150\" w:before=\"480\"/>"
+ "<w:outlineLvl w:val=\"9\"/>"
+ "</w:pPr>"
+ "<w:rPr>"
+ "<w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:cs=\"Arial\"/>"
+ "<w:b/>"
+ "<w:bCs/>"
+ "<w:sz w:val=\"36\"/>"
+ "<w:szCs w:val=\"36\"/>"
+ "</w:rPr>"
+ "</w:style>";
Any ideas on how to fix this exception and generate page numbers in my toc?
EDIT:
I updated the dependencies and now I am still getting the TocException but now with another cause:
Caused by: org.docx4j.openpackaging.exceptions.Docx4JException: Exception exporting package
at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:106)
at org.docx4j.Docx4J.toFO(Docx4J.java:734)
at org.docx4j.toc.TocGenerator.getPageNumbersMapViaFOP(TocGenerator.java:843)
... 97 more
Caused by: java.lang.NullPointerException
at org.docx4j.convert.out.common.preprocess.Containerization.borderChanged(Containerization.java:390)
at org.docx4j.convert.out.common.preprocess.Containerization.bordersChanged(Containerization.java:377)
at org.docx4j.convert.out.common.preprocess.Containerization.groupBodyContent(Containerization.java:204)
at org.docx4j.convert.out.common.preprocess.Containerization.groupAdjacentBorders(Containerization.java:129)
at org.docx4j.convert.out.common.preprocess.Containerization.process(Containerization.java:120)
at org.docx4j.convert.out.common.Preprocess.process(Preprocess.java:165)
at org.docx4j.convert.out.common.AbstractWmlExporter.preprocess(AbstractWmlExporter.java:51)
at org.docx4j.convert.out.common.AbstractWmlExporter.preprocess(AbstractWmlExporter.java:32)
at org.docx4j.convert.out.common.AbstractExporter.export(AbstractExporter.java:63)
Not sure which version of docx4j you are using, but generally, to update page numbers, you need FOP on your classpath.
We broke this in 8.3.3; it is fixed at https://github.com/plutext/docx4j/commit/50cfa5cabe08ab133f28c54b59f73d082d3e80a4#diff-29cfd63b63bfe585aa3468870ca54f1afb6e2246342c396155801b0d0aa9ae43L763
So you could try 8.3.2 with FOP on your classpath.
Alternatively, you could try the approach described at https://www.docx4java.org/blog/2020/03/documents4j-for-toc-update/
See further:
documents4j-local: https://github.com/plutext/docx4j/blob/master/docx4j-samples-documents4j-local/src/main/java/org/docx4j/samples/documents4j/local/TocOperations.java
documents4j-remote: https://github.com/plutext/docx4j/tree/master/docx4j-samples-documents4j-remote

JDK 17 Foreign memory API throws exception - Method threw 'java.lang.UnsatisfiedLinkError' exception

I'm trying to execute the following code using JDK 17.0.1. I have ensured the JDK 17 is on the class path.
Here is the code i'm executing:
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemoryHandles;
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.ResourceScope;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
public class PanamaMain {
public static void main (String[] args) {
MemoryAddress address = MemorySegment.allocateNative(4, ResourceScope.newImplicitScope()).address();
VarHandle handle = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
int value = (int) handle.get(address); //This line throws the exception mentioned above.
System.out.println("Memory Value: " + value);
}
}
The cause of the exception is: java.lang.UnsatisfiedLinkError: 'java.lang.Object java.lang.invoke.VarHandle.get(java.lang.Object[])'
Exception Details
I saw some replies on a similar exception suggesting using the java.library.path system property but I got an error that the java.library.path is an invalid flag.
I would appreciate your help/tips on this issue! Thank you in advance for your time!
The VarHandle.get method is expecting a MemorySegment (not MemoryAddress) and offset in bytes within the segment. The layouts of standard C types are found in CLinker.C_XXX so you don't need to hardcode byte size of int as 4.
Assuming that your PATH is correct for launching JDK17 then this should work:
MemorySegment segment = MemorySegment.allocateNative(CLinker.C_INT, ResourceScope.newImplicitScope());
VarHandle handle = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
handle.set(segment, 0, 4567);
int value = (int)handle.get(segment, 0);
System.out.println("Memory Value: " + value + " = 0x"+Integer.toHexString(value));
Prints:
Memory Value: 4567 = 0x11d7
In JDK17 you can also use MemoryAccess to set or get values from allocated MemorySegment. , and could change to:
MemorySegment segment = MemorySegment.allocateNative(CLinker.C_INT, ResourceScope.newImplicitScope());
MemoryAccess.setInt(segment, -1234);
int value = MemoryAccess.getInt(segment);
System.out.println("Memory Value: " + value + " = 0x"+Integer.toHexString(value));
Prints
Memory Value: -1234 = 0xfffffb2e
Note that the API has changed, so the equivalent code in JDK18+ will be different.

JavaGit Api not Working on Windows

package modifiedlines;
import edu.nyu.cs.javagit.api.DotGit;
import edu.nyu.cs.javagit.api.JavaGitConfiguration;
import edu.nyu.cs.javagit.api.JavaGitException;
import edu.nyu.cs.javagit.api.WorkingTree;
import edu.nyu.cs.javagit.api.commands.GitLogResponse;
import edu.nyu.cs.javagit.api.commands.GitStatus;
import edu.nyu.cs.javagit.api.commands.GitStatusOptions;
import edu.nyu.cs.javagit.api.commands.GitStatusResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
*
* #
author aryan000
*/
public class UseGit {
private static File repositoryDirectory;
private static DotGit dotGit;
public static void main(String s[]) throws JavaGitException, IOException
{
File f = new File("C:\\Program Files\\Git\\bin\\git.exe");
if(!f.exists())
{
System.out.println("does not exist");
}
else
System.out.println("exists at " + f.getPath());
JavaGitConfiguration.setGitPath("C:\\Program Files\\Git\\bin");
System.out.println("Git version : " + JavaGitConfiguration.getGitVersion());
// repositoryDirectory = new File("/home/aryan000/Desktop/retrofit");
repositoryDirectory = new File("/home/aryan000/Desktop/changeprone/changeprone");
System.out.println("Git Repository Location : " + repositoryDirectory.getAbsolutePath());
//get the instance of the dotGit Object
dotGit = DotGit.getInstance(repositoryDirectory);
// System.out.println("checking what i have got ");
// GitLogResponse.CommitFile com ;
// com = (GitLogResponse.CommitFile) dotGit.getLog();
//
// System.out.println(com);
WorkingTree wt = dotGit.getWorkingTree();
File workingTreePath = wt.getPath();
GitStatus gitStatus = new GitStatus();
GitStatusResponse status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
File anotherFileDir = new File("/home/aryan000/Desktop/retrofit/test.txt");
GitStatusOptions options = new GitStatusOptions();
options.setOptOnly(true);
status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
System.out.println("----- Print log to see our commit -----");
for (GitLogResponse.Commit c : dotGit.getLog()) {
System.out.println("commit id is : " + c.getSha());
System.out.println(" commit message is : " + c.getMessage());
System.out.println(" author of the commit is : " + c.getAuthor());
System.out.println(" date modified is : " + c.getDateString());
System.out.println(" number of files changed is : " + c.getFiles());
List<GitLogResponse.CommitFile> store = c.getFiles();
if(store!=null)
System.out.println("the number of files changed is : " + store.size());
System.out.println("list of files changed is : " + c.getFilesChanged());
System.out.println("total number of additions : " + c.getLinesDeleted());
System.out.println("total number of merger : " + c.getMergeDetails());
}
// for(GitLogResponse.CommitFile c : dotGit.getLog())
}
}
Output is shown as :
Exception in thread "main" edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified. { path=[C:\Program Files\Git\bin] }
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:220)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:247)
at modifiedlines.UseGit.main(UseGit.java:40)
Caused by: edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified.
at edu.nyu.cs.javagit.api.JavaGitConfiguration.determineGitVersion(JavaGitConfiguration.java:81)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:217)
... 2 more
Java Result: 1
My query is how to find git logs and the files changed due to a particular commit using a Java Program.
Can any 1 help me in this.
Please See : This code is working fine in Ubuntu i.e. no Path problem still I am unable to get the files changed during a commit. It is give me a List as a null.
This bug was opened a long time ago and just fixed it. Please give it a try , use master branch please, and let me know if it works for you.

how to validate all preflight error for PDF/A-1a in pdfbox

i am working with vaildate PDFA/1A .I followed this code which already exist in this link PDFbox Preflight PDF/A-1b check not working properly in java version 1.8
public class test
{
public static void main(final String[] args) throws Exception
{
File pdfa=new File("D:/DMC-B787-A-00-40-07-00A-008B-D.pdf"); // error pdf
isPDFAdocument(pdfa);
System.out.println("sucess");
}
private static void isPDFAdocument(File pdfa)
{
ValidationResult result = null;
PreflightParser parser;
try
{
parser = new PreflightParser(pdfa);
parser.parse(Format.PDF_A1A);
PreflightDocument documentt = parser.getPreflightDocument();
result = documentt.getResult();
System.out.println("result"+result);
documentt.close();
}
catch (SyntaxValidationException e)
{
result = e.getResult();
}
catch (IOException e)
{
e.printStackTrace();
}
if (result.isValid())
{
System.out.println("The file " + pdfa + " is a valid PDF/A-1a file");
}
else
{
System.out.println("The file" + pdfa + " is not valid, error(s) :");
for (ValidationError error : result.getErrorsList())
{
System.out.println(error.getErrorCode() + " : " + error.getDetails());
}
}
it's not checking the error which mention below .if there it have to show exception but still its vaildate success.
Kindly suggest how to validate all probability preflight error below .how to check it in pdfbox.
Error
CharSet incomplete for Type 1 font (2 matches on 1 page) - 2
Width information for rendered glyphs is inconsistent (2 matches on 1 page) - 2
Document information
File name: "DMC-B787-A-00-40-07-00A-008B-D.pdf"
Path: "C:\Users\wm751e\Documents\Feb19\Synchronize print\Only WDM\Archived doctypes
latest\EA_TBC2016-02-2115.57.49IPD\EA_TBC2016-02-2115.57.49IPD\00"
PDF version number: "1.4"
File size (KB): 114.2
Title: "Illustrated Parts Data - Service Bulletin/Modification List"
Author: "The Boeing Company (PRINTENGINEWEB_BUILD_1.7.49.5.0.0; s1000d_merged_v6.5.36_4.xsl; JobID:)"
Creator: "AH XSL Formatter V6.0 MR7 for Linux64 : 6.0.8.9416 (2013/02/26 10:36JST)"
Producer: "Antenna House PDF Output Library 6.0.389 (Linux64)"
Created: "2/21/2016 3:56 PM"
Modified: "2/21/2016 3:56 PM"
Trapping: "False"
Number of plates: 4
Names of plates: "(Cyan) (Magenta) (Yellow) (Black) "
Environment
Preflight, 15.0.0 (151)
Acrobat version: 15.60
Operating system: Microsoft Windows 7 Service Pack 1 (Build 7601

How to find the local maxima and minima in an image

I am learning how to get the local and global maximum in an image, and as far as know, in one image there is only one global Maximum and one global minimum, and i managed to get these values and their corresponding locations in the image. so my questions are:
how to get the local maxima in an image
how to get the local minima in an image
as you see in the code below, I am using mask, but at run time i receieve the below mentioned error message. so please let me know why do we need mask and how to use it properly.
update:
Line 32 is: MinMaxLocResult s = Core.minMaxLoc(gsMat, mask);
code:
public static void main(String[] args) {
MatFactory matFactory = new MatFactory();
FilePathUtils.addInputPath(path_Obj);
Mat bgrMat = matFactory.newMat(FilePathUtils.getInputFileFullPathList().get(0));
Mat gsMat = SysUtils.rgbToGrayScaleMat(bgrMat);
Log.D(TAG, "main", "gsMat.dump(): \n" + gsMat.dump());
Mat mask = new Mat(new Size(3,3), CvType.CV_8U);//which type i should set for the mask
MinMaxLocResult s = Core.minMaxLoc(gsMat, mask);
Log.D(TAG, "main", "s.maxVal: " + s.maxVal);//to get the global maximum
Log.D(TAG, "main", "s.minVal: " + s.minVal);//to get the global minimum
Log.D(TAG, "main", "s.maxLoc: " + s.maxLoc);//to get the coordinates of the global maximum
Log.D(TAG, "main", "s.minLoc: " + s.minLoc);//to get the coordinates of the global minimum
}
error message:
OpenCV Error: Assertion failed (A.size == arrays[i0]->size) in cv::NAryMatIterator::init, file ..\..\..\..\opencv\modules\core\src\matrix.cpp, line 3197
Exception in thread "main" CvException [org.opencv.core.CvException: ..\..\..\..\opencv\modules\core\src\matrix.cpp:3197: error: (-215) A.size == arrays[i0]->size in function cv::NAryMatIterator::init
]
at org.opencv.core.Core.n_minMaxLocManual(Native Method)
at org.opencv.core.Core.minMaxLoc(Core.java:7919)
at com.example.globallocalmaxima_00.MainClass.main(MainClass.java:32)
In order to calculate global min/max values you don't need to use mask completely.
For calculating local min/max values you can do a little trick. You need to perform dilate/erode operation and then compare pixel value with values of original image. If value of original image and dilated/eroded image are equal therefore this pixel is local min/max.
The code is following:
Mat eroded = new Mat();
Mat dilated = new Mat();
Imgproc.erode(gsMat, eroded, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5,5)));
Imgproc.dilate(gsMat, dilate, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5,5)));
Mat localMin = new Mat(gsMat.size(), CvType.CV_8U, new Scalar(0));
Mat localMax = new Mat(gsMat.size(), CvType.CV_8U, new Scalar(0));
for (int i=0; i<gsMat.height; i++)
for (int j=0; j<gsMat.width; j++)
{
if (gsMat.get(i,j) == eroded.get(i,j))
localMin.put(i,j,255);
if (gsMat.get(i,j) == dilated.get(i,j))
localMax.put(i,j,255);
}
Please note, I'm not a Java programmer. So, code is only illustration of algorithm.

Categories

Resources