0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

クックパッドのURLから写真とレシピQRコード付きの画像一覧を作成するPGM

Last updated at Posted at 2024-07-01

クックパッドのURLから写真とレシピQRコード付きの画像一覧を作成するPGM

クックパッドのURLから写真とレシピQRコード付きの画像一覧を作成するPGMをpythonとpowershellとcmd-batchを 使って作成しました.

2024.07.02 作成手順⑤のPGM内容を修正しました

2024.07.02 作成手順の⑥を追加しました、作成手順②のPGMを修正しました


作成手順

以下の手順で画像リストを作成しました。

1.クックパッドのレシピページから出力したいレシピーのページのURLを並べたテキストファイル
を手動で作成します.

  1. 1で作成したファイルからpowershellスクレイピングで料理名と料理写真の画像URLを並べた
    CSVファイルを作成します

  2. 2で作成したファイルから、料理の画像の一覧をpowershell-PGMでダウンロードします

  3. 1のファイルから各レシピのURL先を表すQRコードの一覧をpython-PGMで作成します

  4. 2と3と1のファイルから、料理名と料理写真とレシピQRコードを合わせた画像の一覧をpython-PGM
    で作成します

  5. 1~5の手順の処理を順番に実行するcmdバッチを作成し、実行する


最終出力画像例

2.jpg


各手順で使用したPGM


2. 1で作成したファイルからpowershellスクレイピングで料理名と料理写真の画像URLを並べた
CSVファイルを作成します

Savehtml2.ps1



function GetImgURLAndRecipeName{
    param($html)

    $SearchStr1 = "<script type='application/ld+json'>"

    $infoLine = ""
    $imgURL = ""
    $recipeName = ""

    for($i=0; $i -lt $html.Length; $i++){
        $line1 = $html[$i]

        if($line1.Contains($SearchStr1)){
            $infoLine = $html[$i+1]
        }
    }

    $infoLine -match """image"":\[""(?<imgURL>.+?)"""
    $imgURL = $Matches.imgURL


    $infoLine -match """name"":\""(?<recipeName>.+?)"""
    $recipeName = $Matches.recipeName


    return $recipeName, $imgURL
}

function main{

    $urlList = Get-Content "C:\クックパッドのレシピURLを並べたファイルのパス" -Encoding UTF8
    $outputFilePath = "C:レシピ名と画像URLのCSVファイルの保存先パス\RecipeNameAndImgURLList.txt"

    $fileContext = @()
    for($i=0; $i -lt $urlList.Length; $i++){
        $url = $urlList[$i]
        Invoke-WebRequest -Uri $url -OutFile "C:\スクレイピング用htmlファイル保存先パス\source1.txt"

        $html = Get-Content "C:\スクレイピング用htmlファイル保存先パス\source1.txt"  -Encoding UTF8
        $retVals = GetImgURLAndRecipeName $html

        $fileContext += $retVals[2] + "," + $retVals[3]

    }

    Write-Output $fileContext | Out-File -FilePath $outputFilePath -Encoding UTF8

}

main

3. 2で作成したファイルから、料理の画像の一覧をpowershell-PGMでダウンロードします

DownloadRecipeImgList.ps1

$URLList = Get-Content C:レシピ名と画像URLCSVファイルパス\RecipeNameAndImgURLList.txt -Encoding UTF8

for($k=0; $k -lt $URLList.Length; $k++){
    $imgUrl = $URLList[$k].Split(',')[1]

    echo $imgUrl

    #写真をダウンロード
    $newFileName = "C:\料理画像の一覧の保存先パス\"+[string]($k+1)
    $newFileName += ".jpg"
    Invoke-WebRequest -Uri $imgUrl -OutFile $newFileName
    
}



4. 1のファイルから各レシピのURL先を表すQRコードの一覧をpython-PGMで作成します

MakeQrCodeImgList.py

import qrcode
import cv2
import qrcode
from PIL import Image

saveQrCodePath = "C:\\作成したQrコードの一覧の保存先パス\\"

idx = 1
f = open('C:レシピ名と画像URLのCSVファイルパス\RecipePageURL.txt', 'r',encoding="UTF-8")
data = f.readlines()
for line1 in data:
    Url = line1
    print(Url)
    
    img = qrcode.make(Url)

    print(type(img))
    print(img.size)
    # <class 'qrcode.image.pil.PilImage'>
    # (290, 290)

    filePath = saveQrCodePath + str(idx) +".png"
    print(filePath)
    print("---")
    img.save(filePath)
    
    # リサイズ前の画像を読み込み
    img = Image.open(filePath)
    # 読み込んだ画像の幅、高さを取得し(100, 100)に
    # 画像をリサイズする
    img_resized = img.resize((100,100))
    # ファイルを保存
    img_resized.save(filePath, quality=90)   
    
    idx = idx+1

f.close()



5. 2と3と1のファイルから、料理名と料理写真とレシピQRコードを合わせた画像の一覧をpython-PGM
で作成します

MakeNewImg3.py

from PIL import Image, ImageFont, ImageDraw
import cv2
import numpy as np

# 画像に文字を入れる関数
def img_add_msg(img, message):
    font_path = 'C:\Windows\Fonts\meiryo.ttc'           # Windowsのフォントファイルへのパス
    font_size = 20                                      # フォントサイズ
    font = ImageFont.truetype(font_path, font_size)     # PILでフォントを定義
    img = Image.fromarray(img)                          # cv2(NumPy)型の画像をPIL型に変換
    draw = ImageDraw.Draw(img)                          # 描画用のDraw関数を用意
 
    # テキストを描画(位置、文章、フォント、文字色(BGR+α)を指定)
    draw.multiline_text((30, 30),
     message, 
     font=font,
      fill=(255, 255, 255, 0),
      stroke_width=2,
      stroke_fill=(0,0,0,255))
    img = np.array(img)                                 # PIL型の画像をcv2(NumPy)型に変換
    return img 

recipeNameFolder = "C:料理名と画像URLの一覧のCSVファイルのパス\\"
imgFolder = "C:料理画像の一覧のファイルのフォルダのパス\\"
qrCodeFolder = "C:レシピURLのQrコード画像のフォルダのパス\\"
newImgFolder = "C:料理名と料理画像とQRコードを合わせた画像の出力先フォルダのパス\\"

recipeNameFilePath = recipeNameFolder + "RecipeNameAndImgURLList.txt"
f = open(recipeNameFilePath, 'r',encoding="UTF-8")
data = f.readlines()

recipeCount = len(data)+1
for fileIdx in range(1, recipeCount, 1):
    line1 = data[(fileIdx-1)]
    recipeName1 = line1.split(',')[0]
    #print(recipeName1)
    
    fileName = str(fileIdx) + ".jpg"
    
    imgUrl = imgFolder + fileName
    img = cv2.imread(imgUrl)
    
    fileName2 = str(fileIdx) + ".png"
    qrCodeUrl = qrCodeFolder + fileName2
    print(qrCodeUrl)
    qrCodeImg = cv2.imread(qrCodeUrl)

    width = 500
    height = 300
    img2 = cv2.resize(img, (width, height))
    img2[height-100:height, width-100:width] = qrCodeImg[0:100, 0:100]
    
    img2 = img_add_msg(img2, recipeName1)
    
    newImgPath = newImgFolder + fileName
    cv2.imwrite(newImgPath, img2)


f.close()
cv2.waitKey(0) 
cv2.destroyAllWindows()

6. 1~5の手順の処理を順番に実行するcmdバッチを作成し、実行する

MakeRecipeImgWithQrCode.cmd

chcp 65001

echo バッチ処理を開始します

cd C:\パワーシェルのパス\powrshell

powershell  -Command C:\パワーシェルのパス\Savehtml2.ps1

powershell  -Command C:\パワーシェルのパス\DownloadRecipeImgList.ps1

cd C:\Python-PGMのパス\MakeQRCode

python MakeQrCodeImgList.py

cd C:\Python-PGMのパス\MakeImgWithQRCode

python MakeNewImg3.py

echo バッチ処理が終わりました

pause

参考にしたページ

比較演算子について - PowerShell | Microsoft Learn

正規表現の最短一致 - Gブログ

PowerShellのファイル出力はこれだけ覚えればOK【上書き・追記】 | 世界を一人で旅するブログ

Python, Pillow, qrcodeでQRコード画像を生成、保存 | note.nkmk.me

【初心者向け】Pythonで画像サイズをリサイズしよう! - AI Academy Media

Python | テキストファイルを読み込む

WindowsでCP932(Shift-JIS)エンコード以外のファイルを開くのに苦労した話 #初心者 - Qiita

Pythonで画像に日本語文字を入れる方法 | WATLAB -Python, 信号処理, 画像処理, AI, 工学, Web-

Python, Pillowで円や四角、直線などの図形を描画 | note.nkmk.me

テキストの書式整形 — Pygame Zero 1.2 ドキュメント

Pythonで縁取り/影付き/透過/ぼかし文字を入れる方法 | WATLAB -Python, 信号処理, 画像処理, AI, 工学, Web-

コマンドプロンプト | キーが押されるまで処理を一時停止(PAUSE)

コマンドプロンプト | 任意の文字列を表示(ECHO)

バッチコマンドで定型処理を行う:超入門コマンドプロンプト(1/3 ページ) - @IT

UTF-8のバッチファイルが文字化けする時の対処3選 – なゆたり

GUIユーザーのためのPowerShell入門(13) コマンドプロンプトからPowerShellスクリプトを実行する | TECH+(テックプラス)

python - Pandas でCSV ファイルの読み込み時にエラー UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 - スタック・オーバーフロー

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?