Ruby Rails Hash Issue - ruby-on-rails
So I have been struggling with an issue for a while now and seem to be getting nowhere...
The problem exists while I am looping through a hash, around the 3rd level deep.
So my code looks a little like:
request[:items][:location_item].each do |locaton_item|
pp location_item[:name]
location_item[:items][:sub_area_option_item].each do |sub_area_option_item|
pp sub_area_option_item[:name]
sub_area_option_item[:items][:option_item].each do |option_item|
option_item[:name] <- THIS IS WHERE MY CODE BREAKS
end
end
end
The reason this is failing is because this particular part of the loop has 2 different variants, one where there is an infinite amount of "option_items" and one where there is only one "option_item". Instead of sending me back the single "option_item" it is looping through this "option_item" and not finding this particular field. Any ideas as how to force it when only one object is found to still return it as an array?
UPDATE(05/092012)
TypeError - Symbol as array index
This error does not appear if I remove the single "option_item" from the hash or even by filtering it with a conditional statement.
As another update that was an example before, here is the code:
request[:items][:house_option_item][:items][:location_option_item].each do |location_option_item|
pp location_option_item.try(:[], :location).try(:[], :name)
# pp location_option_item[:location][:name]
location_option_item[:items][:sub_area_option_item].each do |sub_area_option_item|
pp "--" + sub_area_option_item[:sub_area][:name] + "--" + sub_area_option_item[:sub_area][:id]
count = 0
# pp sub_area_option_item[:items].length
# pp "+++++++++++++++++"
# if sub_area_option_item[:sub_area][:name] != "Conservatory"
[sub_area_option_item[:items][:option_item]].each do |option_item_key_info|
pp "----"
pp option_item_key_info[:usage_name]
end
# end
end
end
Example data(abbreviated):
{:"#xmlns:i"=>"http://www.w3.org/2001/XMLSchema-instance",
:"#xmlns:a"=>"http://schemas.datacontract.org/2004/07/RXTypes",
:items=>
{:house_option_item=>
{:design=>
{:house_style=>nil,
:sales_name=>nil,
:sq_ft=>"0",
:"#xmlns:b"=>"http://schemas.datacontract.org/2004/07/",
:arch_ref=>"D3H102.1",
:marketing_name=>"Warwick",
:num_beds=>"0"},
:items=>
{:location_option_item=>
[{:location=>{:sort_order=>"0", :name=>"Eat", :id=>"1"},
:items=>
{:sub_area_option_item=>
[{:sub_area=>
{:location_id=>"7",
:sort_order=>"0",
:name=>"Conservatory",
:id=>"31"},
:items=>
{:option_item=>
{:lead_days=>"0",
:collection_code=>"NEWHE01",
:usage_name=>"Conservatory",
:max_qty=>"1",
:is_a_bundle=>false,
:only_order_bundle=>false,
:sub_area=>"Conservatory",
:key_info=>
{:specification=>
"PVC-U 'Edwardian' style Conservatory in white with high performance toughened glass double glazed windows and 600mm (approx) dwarf base wall internally and externally. Conservatory to include fan and light, electric heater, double power point and ceramc floor tiling selected from tile choice . Size of Conservatory to be as follows: 3.2 x 3.1 metre (Availabil
ity will be subject to ground levels/conditions)",
:description=>"Conservatory",
:image_url=>"/2012/8/10/334_web.jpg",
:item_id=>"3",
:thumbnail_url=>"/2012/8/10/334_thumb.jpg"},
:build_stage_id=>"0",
:location=>"Building",
:option_flag=>"67",
:bundle_items=>nil,
:price=>"8950",
:choice_items=>nil,
:spec_level=>"85"}}},
{:sub_area=>
{:location_id=>"7",
:sort_order=>"0",
:name=>"Doors",
:id=>"32"},
:items=>
{:option_item=>
[{:lead_days=>"0",
:collection_code=>"NEWHE01",
:usage_name=>"Front Door",
:max_qty=>"0",
:is_a_bundle=>false,
:only_order_bundle=>false,
:sub_area=>"Doors",
:key_info=>
{:specification=>
"GRP pre-finished door with patterned glass manufactured by IG. Style of door to be all as indicated on house plan, finished in solid colour externally & white finish internally. Frame to be UPVC. Please refer to the External Finishing schedule to confirm the external finish selected for each property. The paint finish to be one of the New Heritage Colours - Camouflage beige
- BS381 389, Dk camouflage desert sand - BS381 420, Wine Red - RAL 3005, Braemar - BS4800 - 14C35, Deep Brunswick Green - BS381 227 and White. Door complete with lever handle furniture, multi point lock system, sleeved letterplate, viewer and door chain in black japanned finish externally & chrome lever handle furniture internally.",
:description=>"GRP Front door",
:image_url=>nil,
:item_id=>"4",
:thumbnail_url=>nil},
:build_stage_id=>"0",
:location=>"Building",
:option_flag=>"88",
:bundle_items=>nil,
:price=>"0",
:choice_items=>
{:option_item_key_info=>
[{:specification=>nil,
:description=>"NG42 Diamond",
:image_url=>"/2012/8/21/485_web.jpg",
:item_id=>"211",
:thumbnail_url=>"/2012/8/21/485_thumb.jpg"},
{:specification=>nil,
:description=>"NG21 Square",
:image_url=>"/2012/8/21/486_web.jpg",
:item_id=>"212",
:thumbnail_url=>"/2012/8/21/486_thumb.jpg"},
{:specification=>nil,
:description=>"NG51 Square",
:image_url=>"/2012/8/21/487_web.jpg",
:item_id=>"213",
:thumbnail_url=>"/2012/8/21/487_thumb.jpg"},
{:specification=>nil,
:description=>"NG42 Rectangle",
:image_url=>"/2012/8/21/488_web.jpg",
:item_id=>"214",
:thumbnail_url=>"/2012/8/21/488_thumb.jpg"}]},
:spec_level=>"83"},
{:lead_days=>"0",
:collection_code=>"NEWHE01",
:usage_name=>"Front Door",
:max_qty=>"0",
:is_a_bundle=>false,
:only_order_bundle=>false,
:sub_area=>"Doors",
:key_info=>
{:specification=>
"GRP pre-finished door with patterned glass manufactured by IG. Style of door to be all as indicated on house plan, finished in solid colour externally & white finish internally. Frame to be UPVC. Please refer to the External Finishing schedule to confirm the external finish selected for each property. The paint finish to be one of the New Heritage Colours - Camouflage beige
- BS381 389, Dk camouflage desert sand - BS381 420, Wine Red - RAL 3005, Braemar - BS4800 - 14C35, Deep Brunswick Green - BS381 227 and White. Door complete with lever handle furniture, multi point lock system, sleeved letterplate, viewer and door chain in black japanned finish externally & chrome lever handle furniture internally.",
:description=>"GRP Front door",
:image_url=>nil,
:item_id=>"4",
:thumbnail_url=>nil},
:build_stage_id=>"0",
:location=>"Building",
:option_flag=>"88",
:bundle_items=>nil,
:price=>"0",
:choice_items=>
{:option_item_key_info=>
[{:specification=>nil,
:description=>"NG42 Diamond",
:image_url=>"/2012/8/21/485_web.jpg",
:item_id=>"211",
:thumbnail_url=>"/2012/8/21/485_thumb.jpg"},
{:specification=>nil,
:description=>"NG21 Square",
:image_url=>"/2012/8/21/486_web.jpg",
:item_id=>"212",
:thumbnail_url=>"/2012/8/21/486_thumb.jpg"},
{:specification=>nil,
:description=>"NG51 Square",
:image_url=>"/2012/8/21/487_web.jpg",
:item_id=>"213",
:thumbnail_url=>"/2012/8/21/487_thumb.jpg"},
{:specification=>nil,
:description=>"NG42 Rectangle",
:image_url=>"/2012/8/21/488_web.jpg",
:item_id=>"214",
:thumbnail_url=>"/2012/8/21/488_thumb.jpg"}]},
:spec_level=>"83"},
{:lead_days=>"0",
:collection_code=>"NEWHE01",
:usage_name=>"Front Door",
:max_qty=>"0",
:is_a_bundle=>false,
:only_order_bundle=>false,
:sub_area=>"Doors",
:key_info=>
{:specification=>
"GRP pre-finished door with patterned glass manufactured by IG. Style of door to be all as indicated on house plan, finished in solid colour externally & white finish internally. Frame to be UPVC. Please refer to the External Finishing schedule to confirm the external finish selected for each property. The paint finish to be one of the New Heritage Colours - Camouflage beige
- BS381 389, Dk camouflage desert sand - BS381 420, Wine Red - RAL 3005, Braemar - BS4800 - 14C35, Deep Brunswick Green - BS381 227 and White. Door complete with lever handle furniture, multi point lock system, sleeved letterplate, viewer and door chain in black japanned finish externally & chrome lever handle furniture internally.",
:description=>"GRP Front door",
:image_url=>nil,
:item_id=>"4",
:thumbnail_url=>nil},
:build_stage_id=>"0",
:location=>"Building",
:option_flag=>"88",
:bundle_items=>nil,
:price=>"0",
:choice_items=>
{:option_item_key_info=>
[{:specification=>nil,
:description=>"NG42 Diamond",
:image_url=>"/2012/8/21/485_web.jpg",
:item_id=>"211",
:thumbnail_url=>"/2012/8/21/485_thumb.jpg"},
{:specification=>nil,
:description=>"NG21 Square",
:image_url=>"/2012/8/21/486_web.jpg",
:item_id=>"212",
:thumbnail_url=>"/2012/8/21/486_thumb.jpg"},
{:specification=>nil,
:description=>"NG51 Square",
:image_url=>"/2012/8/21/487_web.jpg",
:item_id=>"213",
:thumbnail_url=>"/2012/8/21/487_thumb.jpg"},
{:specification=>nil,
:description=>"NG42 Rectangle",
:image_url=>"/2012/8/21/488_web.jpg",
:item_id=>"214",
:thumbnail_url=>"/2012/8/21/488_thumb.jpg"}]},
:spec_level=>"83"},
Krista's example will work if there is only one option_item, but not if there's more. I'd add flatten and adjust it to:
[sub_area_option_item[:items][:option_item]].flatten.each do |option_item|
option_item[:name]
end
the [] around it makes sure it's an array. the flatten makes sure that if it already was an array, that you remove the extra layer of [] eg:
['a'].flatten
=> ["a"]
[['a','b','c',]].flatten
=> ["a", "b", "c"]
As far as I can tell, the second part of your loop should be the problem - given your source code and the sample data
01: request[:items][:house_option_item][:items][:location_option_item].each do |location_option_item|
02: location_option_item[:items][:sub_area_option_item].each do |sub_area_option_item|
03: count = 0
04: # if sub_area_option_item[:sub_area][:name] != "Conservatory"
05: [sub_area_option_item[:items][:option_item]].each do |option_item_key_info|
06: pp option_item_key_info[:usage_name]
07: end
08: # end
09: end
10: end
Note that line 01 would end up accessing location_option_item which in your sample above is:
:location_option_item=>
[{:location=>{:sort_order=>"0", :name=>"Eat", :id=>"1"},
:items=>
{:sub_area_option_item=>
[{:sub_area=>
{:location_id=>"7",
:sort_order=>"0",
:name=>"Conservatory",
:id=>"31"},
:items=>
{:option_item=>
{:lead_days=>"0",
:collection_code=>"NEWHE01",
........ etc .......
Notice that location_option_item is the key, which has for value an array.
Thus, my guess is that this line is the problem (02): location_option_item[:items]
Since location_option_item is an array, you cannot access the :items symbol from it.
If you wanted to get items it would be something more like:
location_option_item[1][:items]
Related
Hold apa_table position in Rmarkdown/papaja
I do have another Rmarkdown/papaja package question from my side and would be very happy if anyone was willing to help :) As many people on the internet I have trouble controlling the position of my tables. I have the floatsintext: yes option included in the YAML header. I know that there are LATEX options such as fig.pos = "!H" for which I have to load the float package header-includes: - usepackage\{float} However, doing this I get the following error message: ! LaTeX Error: Unknown float option `H'. Which tells me the float package was not able to load I guess? (I do hav MacTex installed and also the newest R version). What also is absolutely confusing to me is that tables (generated with app_table()) appear in the (approximately) right position when I leave the default spacing, but only appear at the end of my work when I add header-includes: - \usepackage{setspace} - \AtBeginEnvironment{tabular}{\singlespacing} - \AtBeginEnvironment{lltable}{\singlespacing} - \AtBeginEnvironment{tablenotes}{\singlespacing} to the YAML header in order to control the spacing of my tables. I would really appreciate any help! Thanks in advance! Edit: I don't know if this serves the purpose, but if I create the following options, my table appears at the end (and not where it should be) title : "TITLE" shorttitle : "short title" author: - name : "me" affiliation : "1" corresponding : yes # Define only one corresponding author address : "x" email : "y" role: # Contributorship roles (e.g., CRediT, https://casrai.org/credit/) - Conceptualization - Writing - Original Draft Preparation - Writing - Review & Editing # - name : "Ernst-August Doelle" # affiliation : "1,2" # role: # - Writing - Review & Editing affiliation: - id : "1" institution : "" # - id : "2" # institution : "Konstanz Business School" authornote: | Enter author note here. abstract: | keywords : "keywords" wordcount : "X" bibliography : floatsintext : yes figurelist : no tablelist : no footnotelist : no linenumbers : no mask : no draft : no csl: "apa.csl" documentclass : "apa7" classoption : "man" output : papaja::apa6_pdf toc: true header-includes: - \usepackage{float} - \usepackage{setspace} - \AtBeginEnvironment{tabular}{\singlespacing} - \AtBeginEnvironment{lltable}{\singlespacing} - \AtBeginEnvironment{tablenotes}{\singlespacing} --- {r setup, include = FALSE} library("papaja") library("apa") library("tidyverse") library("apaTables") r_refs("r-references.bib") {r analysis-preferences} # Seed for random number generation set.seed(42) knitr::opts_chunk$set(cache.extra = knitr::rand_seed) {r} cor_table <- apa.cor.table(iris) Text BLABLABLABLA {r tab, results = "asis", fig.pos = "!h"} apa_table(cor_table$table.body, caption = "Means, standard deviations, and correlations with confidence intervals for study variables.", note = "Note. M and SD are used to represent mean and standard deviation, respectively.Values in square brackets indicate the 95% confidence interval.The confidence interval is a plausible range of population correlations that could have caused the sample correlation (Cumming, 2014). * indicates p < .05. ** indicates p < .01.", font_size = "footnotesize", row.names = F, placement = "p") # Methods We report how we determined our sample size, all data exclusions (if any), all manipulations, and all measures in the study. <!-- 21-word solution (Simmons, Nelson & Simonsohn, 2012; retrieved from http://ssrn.com/abstract=2160588) --> ## Participants ## Material ## Procedure ## Data analysis We used `r cite_r("r-references.bib")` for all our analyses. # Results # Discussion \newpage # References \begingroup \setlength{\parindent}{-0.5in} \setlength{\leftskip}{0.5in} <div id="refs" custom-style="Bibliography"></div> \endgroup
For PDF output, there is a recommended way to customize the placement of tables created via apa_table(). (You do not have to load the float package via header includes.) First, set the YAML header option floatsintext: yes. Second, when creating your table with apa_table(), use the function's placement argument: ```{r tab} apa_table(cor_table$table.body, caption = "Means, standard deviations, and correlations with confidence intervals for study variables.", note = "Note. M and SD are used to represent mean and standard deviation, respectively.Values in square brackets indicate the 95% confidence interval.The confidence interval is a plausible range of population correlations that could have caused the sample correlation (Cumming, 2014). * indicates p < .05. ** indicates p < .01.", font_size = "footnotesize", row.names = F, placement = "H")
How to cycle through multidimensional array in rails
Im working on implementing searchkick in my project and got the search to work fine. Now Im trying to implement a filter system and use the aggs to display the filter criteria. The array that the aggs returns is a little complex for me and trying to figure out how to cycle through the specific parts. Heres the aggs it returns: {"techniques"=>{"doc_count_error_upper_bound"=>0, "sum_other_doc_count"=>0, "buckets"=>[{"key"=>"Frying", "doc_count"=>1}, {"key"=>"Searing", "doc_count"=>1}]}, "ingredients"=>{"doc_count_error_upper_bound"=>0, "sum_other_doc_count"=>0, "buckets"=>[{"key"=>"Furikake, for serving", "doc_count"=>1}, {"key"=>"Kosher salt and ground black pepper", "doc_count"=>1}, {"key"=>"Salmon fillets", "doc_count"=>1}, {"key"=>"avocado, diced", "doc_count"=>1}, {"key"=>"cooked white rice", "doc_count"=>1}, {"key"=>"japanese cucumber", "doc_count"=>1}, {"key"=>"teriyaki sauce", "doc_count"=>1}, {"key"=>"to 8 scallions, thinly sliced", "doc_count"=>1}, {"key"=>"vegetable oil", "doc_count"=>1}]}, "cuisines"=>{"doc_count_error_upper_bound"=>0, "sum_other_doc_count"=>0, "buckets"=>[{"key"=>"Asian", "doc_count"=>1}, {"key"=>"Japanese", "doc_count"=>1}]}} How would I write a do loop to cycle through just the cuisines part and pull out the individual names and counts from the buckets: "cuisines"=>{"doc_count_error_upper_bound"=>0, "sum_other_doc_count"=>0, "buckets"=>[{"key"=>"Asian", "doc_count"=>1}, {"key"=>"Japanese", "doc_count"=>1}]}} So basically I want a list that would look like this: Asian(1) Japanese(1)
What you have is a hash with array elements. It depends what you exactly you want, but assuming you assigned it a variable my_hash, you can do this for example: my_hash['cuisines']['buckets'].reduce('') do |r, h| r += "#{h['key']} (#{h['doc_count']}) " end => "Asian (1) Japanese (1) "
Improve accuracy of underlined text
Some underlines in my image are very close to the text. For that particular text tesseract is unable to produce accurate results. I have attached the image and text file. Is there any way i can increase accuracy of the text? I have tried to remove the underlines with some of the image processing techniques, but the problem is those lines which are close to the text are not getting removed. And are there any parameters in tesseract which i can use to improve the accuracy? Thanks in advance. image which i am trying to run Its Result: ARR! D. 1. \OCIJHJO‘LI'IJ?‘ 3.. 10. E. F. SITE NUMBER ARCHEOLOGICAL DESCRIPTION General site description SITE IS COVERED WITH LARGE PINES AND IS IN RELATIVLY GOOD CONDITION, snowING'EITTrE‘SIGNS‘OFTRosmN—EXCEPT—AEONG-Tmm _"—""NHERE IT DROPS or INTO FLOODPLAIN OF CREEK THERE ARE A EEN ANIMAL TRAILS THAT HAVE APPARENTLY ERODED OUT IN THE PAST. ONE OF THESE WAS QUIET DEEP ACCORDING “TO AUGER TEST, BUT HAS FILLED UP WITH SAND AND GROWN OVER AGAIN. FIRST AUGER TEST “WAS INTO THIS DEE P"GULLY" AND GAVE A FALSE IMPRESSION AS TO THE TRUE DEPTH OF SITE. THIS TEST HOLE PRODUCED LIEHLQ FLAKES ALL THE WAY DOWN TO 42 INCHES AND _m STERILE SAND DOWN TO 60 INCHES= REST OF SITE PRODUCED SAND AND CHIPS ONLY TO l- an I ' A: : I L I i : ‘5!) THIS 3 1.0 5.- 3.. 'Y __ FINE SITE. Site size .AT L S - E Y CONSIDERABLY MQBE Nature of archeological deposition EAIBIEIHNDESTURBED EXCEPT ALONG THE EDGES OF SITE T D0. Site depth. 20-22 INCHES Hidden Faunal preservation Floral preservation Human remains Cultural features (type and number) Charcoal preservation DATA RECOVERY METHODS Ground surface visibility: 0% x 1-251 26—50% 51-75% 76—100% Description of ground cover iMATURE PINE FOREST Time spent collecting Number of peeple collecting Description of surface collecting methods Type and extent of testing and/or excavation FIVE TEST HOLES WERE SUNK IN SITE WITH 8" AUGERa THESE WERE TAKEN DOWN IN 6" LEVELS UNTIL STERILE CLAY WAS REACHED. DIRTTA T- FROM EACH 6" LEVEL WAS SCREENED THROUGH_l/4" WIRE MESH AND ARTIFACTS KEPT FOR ANALYSIS. ALL TEST HOLES QERE PLQIIED EIIE TRANSIT IN RELATION TO DATUM MARKER WHI IS A PIPE ‘ _ -: fl' : 3:0. . .: U' J I: : : . !" uFF 3L GROUND. P__\l: IS I : um \I' :i “I ' I ' .M' I ' D' . I’ I 2! ti 0 .1. ' -. _ .L l' . ARCHEOLOGICAL COMPONENTS Paleo-Indian Late Whodland 17th century Early Archaic Mississippian 18th century Middle Archaic Late prehistoric 19th century Late Archaic Unknown prehistoric ___ 20th century __ Early Woodland Ceramic prehistoric ____ Unknown historic Middle Woodland 16th century
Remove legend bar in R using Image.Plot
This is the test code im using x_coord <- c(1,2,3,4) y_coord <- c(1,2,3,4) value <- c(12,15,19,30) foo <- data.frame(x_coord, y_coord, value) library(MBA) foo=foo[ order(foo[,1], foo[,2],foo[,3]), ] mba.int <- mba.surf(foo, 300, 300, extend=T)$xyz.est library(fields) fields::image.plot(mba.int,legend.only = FALSE, axes=FALSE) The axes part deletes the axis, but when i try to remove the legend bar, the vertical bar indicating the color measurements, it will not go away. i have tried smallplot = 1, but that gives me an error but it gets rid of the vertical legend, Anyone have any idea of how to get rid of the legend without any errors produced ?
If you don't want the color legend, just use the built-in image function instead. The function you are using is designed specifically for adding a legend easily. If you want to keep the same color scheme as the fields image.plot function: image(<your data>, ..., col = tim.colors()) Using this creates the exact same image without a legend.
The image and image.plot functions actually have quite different plotting functionality. One problem (at least for me, trying to plot regional climate model data) with using the built-in image is that it cannot handle irregular grids. The image.plot function uses the poly.image function internally to create the plot. Both are included in the fields package. The good thing is that the poly.image function also can be used on its own, for example like this: library("fields") # create an example of an irregular 3x3 grid by adding random perturbations up to ±0.6 x <- matrix(rep(1:3,each=3) + 0.6*runif(9), ncol=3) y <- matrix(rep(7:9,times=3) + 0.6*runif(9), ncol=3) # 9 values, from 1 to 9 z <- matrix(1:9,nrow=3) # Please avoid the default rainbow colours, see e.g. # https://www.climate-lab-book.ac.uk/2014/end-of-the-rainbow/ # Other examples of colour schemes: https://colorbrewer2.org/ col <- colorRampPalette(c("#2c7bb6","#abd9e9","#ffffbf","#fdae61","#d7191c"))(9) par(mfrow=c(1,3), mar=c(4,4,4,1), oma=c(0,0,0,0)) image(x=7:9,y=1:3,z,col=col, main="image()\n Only regular grid. Also note transposition.") image.plot(x,y,z,col=col, main="image.plot()\n Always with colorbar.") poly.image(x,y,z,col=col, main="poly.image()\n Does not include colorbar.")
Mathematica's TextRecognize not up to par
Please take a look at the screenshot below and see if you can tell me why this won't work. The examples in on the reference page for TextRecognize look pretty impressive, I don't think recognizing single letters like this should be a problem. I've tried resizing the letters as well as having the image sharpened. For convenience in case you want to try this yourself I have included the image that I use at the bottom of this post. You can also find plenty more like this by searching for "Wordfeud" in Google Image Search.
Very cool question! TextRecognize uses heuristics to recognize whole words from the English language. This is the gotcha that makes recognizing single letters very hard Consider the following line of thought: s = Import["http://i.stack.imgur.com/JHYuh.png"]; p = ImagePartition[s, 32] Now pick letters to form the English word 'EXIT': x = {p[[1, 13]], p[[6, 6]], p[[3, 13]], p[[1, 12]]} Now clean up these images a bit, like so: d = ImageAssemble[ Map[ImageTake[#, {3, 27}, {2, 20}] &, x ]]; Then this returns the string "EXIT": TextRecognize[d]
This is an approach completely different from using TextRecognize, so I am posting this as a separate answer. It uses the same image recognition technique from the How do I find Waldo with Mathematica. First get the puzzle: wordfeud = Import["http://i.stack.imgur.com/JHYuh.png"] And then get the pieces of the puzzle: Grid[pieces = ImagePartition[s, 32]] Let's be interested in the letter E: LetterE = pieces[[4, 3]] Get the correlation image: correlation = ImageCorrelate[wordfeud, Binarize[LetterE], NormalizedSquaredEuclideanDistance] And highlight the matches: positions = Dilation[ColorNegate[Binarize[correlation, .1]], DiskMatrix[20]]; found = ImageMultiply[wordfeud, ImageAdd[ColorConvert[positions, "GrayLevel"], .5]] As before, this requires a bit of tuning on binarizing the correlation image, but other than that this should help to identify bits and pieces of this puzzle.
I thought the quality of your image might be interfering. Binarizing your image did not help : recognition was zilch. I also tried a very sharp black and white image of a crossword puzzle solution. (see below) Again, nothing was recognized whether in regular or binarized format. So I removed the black background leaving only the letters and their thin black frames. Again, recognition was about 0%. When I removed the frames from around some of the letters AND binarized the image the only parts that were recognizable were those regions in which there was nothing but letters. (see below) Notice in the output below, ANTS, TIRES, and TEXAS are correctly identified (as well as VECTORS), but just about nothing else. Notice also that, even though the strings were widely spaced, mma interpreted them as words, rather than separate letters. Note "TEXAS" instead of "T E X A S". TextRecognize[Binarize#img] (* output *) ANTS FFWWW FEEWF E R o If IU I? E A FI5F WWWFF 5 5552? L E F F T s E NTT BT| H0RWW#0WVlWF;EE F 5 W E ; OCS FOFT W W R AL%AE A TT I T ? _ i iE#W'NF WG%S W A A EW F I i SWWTW W ALTFCWD N H A V 5 A F F PLATT EWWLIGHT W N E T HE TIRES C TEXAS VECTORS I didn't have the patience to completely clean up the image. It would have been much faster to retype the text by hand. Conclusion: Don't use text recognition in mma unless you have absolutely clear text against an even-colored, bright, preferrably white, background. The results also varied depending on the file format used. Avoid .pdf altogether. Edit acl captured and tried to recognize the last 5 lines (above Edit). His results (in a comment below): mostly gibberish. I decided to do the same. But since Prashant warned that text size makes a difference, I zoomed in first so that the text appear (to my eyes) to be about 20 pica. Below is the picture of the text I scanned and TextRecognized. Here's the result of an unbinarized TextRecognize (at that large size): Gliii. Q lk-ii`t`*¥ if EY £\[CloseCurlyDoubleQuote]1\[Euro]'EE \ Di'¥C~E\"P ITF SKI' T»f}!E'!',IL:?E\[CloseCurlyDoubleQuote] I 2 VEEE5\ \[CloseCurlyQuote] LEP \"- \"VE 1. ur e=\\..r.1.»».»\\\\ rw r 1»»\\|a'*r | r .fm -»'-an \ \[OpenCurlyQuote] -.-rr -_.»~|-.'i~-.w~,.-- nv n.w~»-\ \[OpenCurlyDoubleQuote]~" Now, here's the result for the TextRecognize of the binarized image. The original image was a .png from Jing. I didn't have the patience to completely clean up the image. It would \ have been much faster to retype the text by hand. Conclusion: Don't use text recognition in mma unless you have \ absolutely clear text against an even- colored, bright, preferrably white, background. The results also varied depending on the file format used. Avoid .pdf \ altogether.