Google Earth Engine: error “Invalid type. Expected type: Number” trying to compute a Number while performing histogram matching on satellite images

I am working on satellite imagery on Google Earth Engine (JavaScript), and I’m experiencing some issues while I try to perform histogram matching on two images from two different time periods.
In particular, when I retrieve the histograms for the two images (different histograms for different spectral bands) I see that the histograms of one image are shorter than the histograms of the other image. So, I tried to compute the minimum length between the histograms from the two images to slice the longest histogram and match the length of the shortest one.
I admit I exploited chatGPT to get help while developing the script (I am a beginner in JavaScript), as the only examples provided by Google Earth Engine tutorials on this subject are in Python and I needed to translate in JavaScript (https://developers.google.com/earth-engine/tutorials/community/histogram-matching).

This is the script that I’m using:

// Function for histograms lookup table 
function lookup(source_hist, target_hist) {   // in our case: source_hist is histYear2, target_hist is histYear1 (match year2 with year1)

  
  var source_values = source_hist.slice(1, 0, 1).project([0]); // 1D array of the unique pixel values from the source image histogram
  var source_counts = source_hist.slice(1, 1, 2).project([0]); // 1D array of the normalized counts corresponding to source_values

  var target_values = target_hist.slice(1, 0, 1).project([0]);
  var target_counts = target_hist.slice(1, 1, 2).project([0]);
  
  // Ensure the counts are equal in length
  var lengthSource = ee.Number(source_counts.length());
  var lengthTarget = ee.Number(target_counts.length());
  print("source length object type: ", ee.Algorithms.ObjectType(lengthSource));
  print("source length object type: ", ee.Algorithms.ObjectType(lengthTarget))
  
  // Compute the minimum length and convert it to an Earth Engine integer
  var minLength = ee.Algorithms.If(
    lengthSource.lt(lengthTarget), 
    lengthSource.toInt(), 
    lengthTarget.toInt()
  );
  print(minLength);
  
  // Slice to equal length
  source_values = source_values.slice(0, 0, minLength);
  source_counts = source_counts.slice(0, 0, minLength);
  target_values = target_values.slice(0, 0, minLength);
  target_counts = target_counts.slice(0, 0, minLength);

  // Normalize the counts: this normalization converts the counts into probabilities or proportions.
  source_counts = source_counts.divide(source_counts.reduce(ee.Reducer.sum(), [0]));
  target_counts = target_counts.divide(target_counts.reduce(ee.Reducer.sum(), [0]));

  var lookUp = source_counts.toList().map(function(n) { // for each n (a normalized count from the source histogram), we find a corresponding value from the target histogram
    return target_values.get(target_counts.gte(n).argmax());  
  });                                                         

  return {x: source_values.toList(), y: lookUp};
}
  
// Function to match histogram for a single band
function matchHistogram(bandName, year1, year2, scale) { 

  // Compute histograms for the selected band
  var histYear1 = ee.Array(year1.select(bandName).reduceRegion({
    reducer: ee.Reducer.autoHistogram({maxBuckets: 256}), 
    geometry: year1.geometry(),                           
    scale: scale,                                         
    maxPixels: 65536 * 4 - 1
  }).get(bandName));
  print('Histogram Year 1 for', bandName, histYear1);
  
  var histYear2 = ee.Array(year2.select(bandName).reduceRegion({
    reducer: ee.Reducer.autoHistogram({maxBuckets: 256}),
    geometry: year2.geometry(),
    scale: scale,   
    maxPixels: 65536 * 4 - 1
  }).get(bandName));
    print('Histogram Year 2 for', bandName, histYear2);
  
  
  // Generate the lookup table
  var lookupTable = lookup(histYear1, histYear2); // Note the order, matching hist2 to hist1 (so year2 to year1)
  // Print the lookup table for inspection
  // Note: This is for one band, modify as needed to inspect other bands
  print('Lookup Table for', bandName, lookupTable);

  // Apply the lookup table to match year2 histogram to year1 histogram and perform the interpolation.
  var matchedBand = year2.select(bandName).interpolate({
    x: lookupTable.x,
    y: lookupTable.y
  }).rename(bandName);
  print('Matched Band for', bandName, matchedBand);

  return matchedBand;
}


// List of PlanetScope band names
// b1: coastal blue, b2: blue, b3: green I, b4: green, b5: yellow, b6: red, b7: rededge, b8: Near-IR
var bands = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8'];
// spatial resolution (meters)
var scale = 3; 


// Match histograms for all bands
var matchedBands = bands.map(function(bandName) {
  return matchHistogram(bandName, year1, year2, scale);
});

// Combine matched bands into a single image
var matchedYear2 = ee.Image.cat(matchedBands).rename(bands);
print("matched", matchedYear2);

Apparently the problem is related to the calculation of the minimum length (minLength) object, to use as the “end” argument in the .slice() function.
When running the script, this is what appears in the Console:

Histogram Year 1 for
b1
List (179 elements)

Histogram Year 2 for
b1
List (183 elements)

source length object type:
Array

source length object type:
Array

ComputedObject (Error)
Number.lt, argument ‘left’: Invalid type.
Expected type: Number.
Actual type: Long<0, 4294967295, dimensions=1>.
Actual value: [179]

One thing I do not understand is why the ee.Algorithms.ObjectType() functions return “Array” when I used ee.Number to retrieve the length of the arrays as a number.
Moreover, the Error refers to this snippet:

// Compute the minimum length and convert it to an Earth Engine integer
  var minLength = ee.Algorithms.If(
  lengthSource.lt(lengthTarget), 
  lengthSource.toInt(), 
  lengthTarget.toInt()
  );

Where I used also .toInt() to ensure the number was transformed into an integer.

I thank in advance whoever could help me in understanding my mistake and improve my code (I’m starting to think that there is a much simpler way to do this).

New contributor

Aurora Bozzini is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Google Earth Engine: error “Invalid type. Expected type: Number” trying to compute a Number while performing histogram matching on satellite images

I am working on satellite imagery on Google Earth Engine (JavaScript), and I’m experiencing some issues while I try to perform histogram matching on two images from two different time periods.
In particular, when I retrieve the histograms for the two images (different histograms for different spectral bands) I see that the histograms of one image are shorter than the histograms of the other image. So, I tried to compute the minimum length between the histograms from the two images to slice the longest histogram and match the length of the shortest one.
I admit I exploited chatGPT to get help while developing the script (I am a beginner in JavaScript), as the only examples provided by Google Earth Engine tutorials on this subject are in Python and I needed to translate in JavaScript (https://developers.google.com/earth-engine/tutorials/community/histogram-matching).

This is the script that I’m using:

// Function for histograms lookup table 
function lookup(source_hist, target_hist) {   // in our case: source_hist is histYear2, target_hist is histYear1 (match year2 with year1)

  
  var source_values = source_hist.slice(1, 0, 1).project([0]); // 1D array of the unique pixel values from the source image histogram
  var source_counts = source_hist.slice(1, 1, 2).project([0]); // 1D array of the normalized counts corresponding to source_values

  var target_values = target_hist.slice(1, 0, 1).project([0]);
  var target_counts = target_hist.slice(1, 1, 2).project([0]);
  
  // Ensure the counts are equal in length
  var lengthSource = ee.Number(source_counts.length());
  var lengthTarget = ee.Number(target_counts.length());
  print("source length object type: ", ee.Algorithms.ObjectType(lengthSource));
  print("source length object type: ", ee.Algorithms.ObjectType(lengthTarget))
  
  // Compute the minimum length and convert it to an Earth Engine integer
  var minLength = ee.Algorithms.If(
    lengthSource.lt(lengthTarget), 
    lengthSource.toInt(), 
    lengthTarget.toInt()
  );
  print(minLength);
  
  // Slice to equal length
  source_values = source_values.slice(0, 0, minLength);
  source_counts = source_counts.slice(0, 0, minLength);
  target_values = target_values.slice(0, 0, minLength);
  target_counts = target_counts.slice(0, 0, minLength);

  // Normalize the counts: this normalization converts the counts into probabilities or proportions.
  source_counts = source_counts.divide(source_counts.reduce(ee.Reducer.sum(), [0]));
  target_counts = target_counts.divide(target_counts.reduce(ee.Reducer.sum(), [0]));

  var lookUp = source_counts.toList().map(function(n) { // for each n (a normalized count from the source histogram), we find a corresponding value from the target histogram
    return target_values.get(target_counts.gte(n).argmax());  
  });                                                         

  return {x: source_values.toList(), y: lookUp};
}
  
// Function to match histogram for a single band
function matchHistogram(bandName, year1, year2, scale) { 

  // Compute histograms for the selected band
  var histYear1 = ee.Array(year1.select(bandName).reduceRegion({
    reducer: ee.Reducer.autoHistogram({maxBuckets: 256}), 
    geometry: year1.geometry(),                           
    scale: scale,                                         
    maxPixels: 65536 * 4 - 1
  }).get(bandName));
  print('Histogram Year 1 for', bandName, histYear1);
  
  var histYear2 = ee.Array(year2.select(bandName).reduceRegion({
    reducer: ee.Reducer.autoHistogram({maxBuckets: 256}),
    geometry: year2.geometry(),
    scale: scale,   
    maxPixels: 65536 * 4 - 1
  }).get(bandName));
    print('Histogram Year 2 for', bandName, histYear2);
  
  
  // Generate the lookup table
  var lookupTable = lookup(histYear1, histYear2); // Note the order, matching hist2 to hist1 (so year2 to year1)
  // Print the lookup table for inspection
  // Note: This is for one band, modify as needed to inspect other bands
  print('Lookup Table for', bandName, lookupTable);

  // Apply the lookup table to match year2 histogram to year1 histogram and perform the interpolation.
  var matchedBand = year2.select(bandName).interpolate({
    x: lookupTable.x,
    y: lookupTable.y
  }).rename(bandName);
  print('Matched Band for', bandName, matchedBand);

  return matchedBand;
}


// List of PlanetScope band names
// b1: coastal blue, b2: blue, b3: green I, b4: green, b5: yellow, b6: red, b7: rededge, b8: Near-IR
var bands = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8'];
// spatial resolution (meters)
var scale = 3; 


// Match histograms for all bands
var matchedBands = bands.map(function(bandName) {
  return matchHistogram(bandName, year1, year2, scale);
});

// Combine matched bands into a single image
var matchedYear2 = ee.Image.cat(matchedBands).rename(bands);
print("matched", matchedYear2);

Apparently the problem is related to the calculation of the minimum length (minLength) object, to use as the “end” argument in the .slice() function.
When running the script, this is what appears in the Console:

Histogram Year 1 for
b1
List (179 elements)

Histogram Year 2 for
b1
List (183 elements)

source length object type:
Array

source length object type:
Array

ComputedObject (Error)
Number.lt, argument ‘left’: Invalid type.
Expected type: Number.
Actual type: Long<0, 4294967295, dimensions=1>.
Actual value: [179]

One thing I do not understand is why the ee.Algorithms.ObjectType() functions return “Array” when I used ee.Number to retrieve the length of the arrays as a number.
Moreover, the Error refers to this snippet:

// Compute the minimum length and convert it to an Earth Engine integer
  var minLength = ee.Algorithms.If(
  lengthSource.lt(lengthTarget), 
  lengthSource.toInt(), 
  lengthTarget.toInt()
  );

Where I used also .toInt() to ensure the number was transformed into an integer.

I thank in advance whoever could help me in understanding my mistake and improve my code (I’m starting to think that there is a much simpler way to do this).

New contributor

Aurora Bozzini is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật