gpt4 book ai didi

java - 在java中循环遍历两个矩阵

转载 作者:行者123 更新时间:2023-12-04 10:14:37 26 4
gpt4 key购买 nike

我是java和一般编程的新手,我有一个从Android图像识别文本的项目。我在 Android Studio 中工作,目前我有两个矩阵——一个是从设备库中获取的源图像的值,一个是模板图像的值。矩阵中的值基本上是像素的颜色,以灰度工作,分为6个区间:255-214的颜色值等于0,172-213的颜色值等于0.2,129-171的颜色值等于0.4等。

我需要在两个矩阵中逐行进行并对其进行一些计数-在源矩阵的第一行中取第一个值,在模板矩阵的第一行中取第一个值,并在公式中使用它:

nIntensity = 1 - abs(template_value - source_value)

并对一行中的所有值执行此操作,然后对这些值求和并转到第二行并执行相同操作(导致 x 矩阵行的 x nIntensity 值数组)。我一开始尝试的是使用嵌套循环,但我对它们有点过分了:
for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
for(int sColumn = 0; sColumn < 1; sColumn++) {
for(int pRow = 0; pRow < patternMatrix.length; pRow++) {
for(int pColumn = 0; pColumn < 1; pColumn++) {
nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));}}}}

这导致 nIntensity 变量的值太高 - 对于 sourceMatrix 和 patternMatrix 有 56 个值等于 1.0 我应该得到数字 56 的结果,而不是我得到 3192,这意味着它通过所有循环的次数太多。与 sColumn < 1pColumn < 1我试图从一开始就变得简单,只取两个矩阵的第一行,然后再深入研究它并使用多行。

在做了一些研究之后,我试着用代码让它变得非常简单:
for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
for (int sColumn = 0; sColumn < 1; sColumn++) {
nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
System.out.println("Result: " + nIntensity);}}

当我在每个循环之后打印结果实际上得到结果 56 时,它会崩溃并出现异常

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=56; index=56

最佳答案

您以错误的方式嵌套了循环。

代替

for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
for(int sColumn = 0; sColumn < 1; sColumn++) {
for(int pRow = 0; pRow < patternMatrix.length; pRow++) {
for(int pColumn = 0; pColumn < 1; pColumn++) {
nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));}}}}


for(int sRow = 0, pRow=0; sRow < sourceMatrix.length && pRow < patternMatrix.length; sRow++, pRow++) {
for(int sColumn = 0; sColumn < 1; sColumn++) {
nIntensity += (1 - abs(patternMatrix[pRow][pColumn] - sourceMatrix[sRow][sColumn]));
}
}

此外,在以下代码块中,您没有检查 patternMatrix 的边界。 .替换此代码块
for(int sRow = 0; sRow < sourceMatrix.length; sRow++) {
for (int sColumn = 0; sColumn < 1; sColumn++) {
nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
System.out.println("Result: " + nIntensity);}}


for(int sRow = 0; sRow < sourceMatrix.length && sRow < patternMatrix.length; sRow++) {
for (int sColumn = 0; sColumn < 1; sColumn++) {
nIntensity += (1 - abs(patternMatrix[sRow][sColumn] - sourceMatrix[sRow][sColumn]));
System.out.println("Result: " + nIntensity);
}
}

关于java - 在java中循环遍历两个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61139299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com